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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.ncmp.impl.inventory
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.LcmEventProducer
39 import org.onap.cps.utils.JsonObjectMapper
40 import org.slf4j.LoggerFactory
41 import spock.lang.Specification
43 import static org.onap.cps.api.parameters.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
44 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
45 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
46 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
47 import static org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse.Status
48 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME
49 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
51 class CmHandleRegistrationServicePropertyHandlerSpec extends Specification {
53 def mockInventoryPersistence = Mock(InventoryPersistence)
54 def mockCpsDataService = Mock(CpsDataService)
55 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
56 def mockAlternateIdChecker = Mock(AlternateIdChecker)
57 def mockCmHandleIdPerAlternateId = Mock(IMap)
58 def mockLcmEventProducer = Mock(LcmEventProducer)
60 def objectUnderTest = new CmHandleRegistrationServicePropertyHandler(mockInventoryPersistence, mockCpsDataService, jsonObjectMapper, mockAlternateIdChecker, mockCmHandleIdPerAlternateId, mockLcmEventProducer)
61 def logger = Spy(ListAppender<ILoggingEvent>)
64 def setupLogger = ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class))
65 setupLogger.addAppender(logger)
66 setupLogger.setLevel(Level.DEBUG)
68 // Always accept all alternate IDs
69 mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
73 ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class)).detachAndStopAllAppenders()
76 def static cmHandleId = 'myHandle1'
77 def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
79 def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
80 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
81 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
82 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
83 def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes, leaves: ['id': cmHandleId])]
85 def 'Update CM Handle Public Properties: #scenario'() {
86 given: 'the CPS service return a CM handle'
87 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
88 and: 'an update cm handle request with public properties updates'
89 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
90 when: 'update data node leaves is called with the update request'
91 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
92 then: 'the replace list method is called with correct params'
93 1 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
95 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
96 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
99 where: 'following public properties updates are made'
100 scenario | updatedPublicProperties || expectedPropertiesAfterUpdate
101 'property added' | ['newPubProp1': 'pub-val'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
102 'property updated' | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
103 'property removed' | ['publicProp4': null] || [['publicProp3': 'publicValue3']]
104 'property ignored(value is null)' | ['pub-prop': null] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
107 def 'Update Additional Properties: #scenario'() {
108 given: 'the CPS service return a CM handle'
109 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
110 and: 'an update cm handle request with additional properties updates'
111 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, additionalProperties: updatedAdditionalProperties)]
112 when: 'update data node leaves is called with the update request'
113 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
114 then: 'replace list method should is called with correct params'
115 expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
117 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
118 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
121 where: 'following additional properties updates are made'
122 scenario | updatedAdditionalProperties || expectedPropertiesAfterUpdate | expectedCallsToReplaceMethod
123 'property added' | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
124 'property updated' | ['additionalProp1': 'newValue'] || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']] | 1
125 'property removed' | ['additionalProp1': null] || [['additionalProp2': 'additionalValue2']] | 1
126 'property ignored(value is null)' | ['new-prop': null] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 1
127 'no property changes' | [:] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 0
130 def 'Update CM Handle Properties, remove all public properties: #scenario'() {
131 given: 'the CPS service return a CM handle'
132 def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId], childDataNodes: originalPropertyDataNodes)
133 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [cmHandleDataNode]
134 and: 'an update cm handle request that removes all public properties(existing and non-existing)'
135 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
136 when: 'update data node leaves is called with the update request'
137 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
138 then: 'the replace list method is not called'
139 0 * mockInventoryPersistence.replaceListContent(*_)
140 then: 'delete data node will be called for any existing property'
141 expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
143 assert arg[0].contains("@name='publicProp")
146 where: 'following public properties updates are made'
147 scenario | originalPropertyDataNodes || expectedCallsToDeleteDataNode
148 '2 original properties, both removed' | propertyDataNodes || 2
149 'no original properties' | [] || 0
152 def '#scenario error leads to #exception when we try to update cmHandle'() {
153 given: 'cm handles request'
154 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], additionalProperties: [:])]
155 and: 'data node cannot be found'
156 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> { throw exception }
157 when: 'update data node leaves is called using correct parameters'
158 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
159 then: 'one failed registration response'
161 and: 'it has expected error details'
162 with(response.get(0)) {
163 assert it.status == Status.FAILURE
164 assert it.cmHandle == cmHandleId
165 assert it.ncmpResponseStatus == expectedError
166 assert it.errorText == expectedErrorText
169 scenario | cmHandleId | exception || expectedError | expectedErrorText
170 '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'
171 'Unknown' | 'cmHandleId' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
172 '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'
175 def 'Multiple update operations in a single request'() {
176 given: 'cm handles request'
177 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:]),
178 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:]),
179 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:])]
180 and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
181 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> cmHandleDataNodeAsCollection >> {
182 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
183 when: 'update data node leaves is called using correct parameters'
184 def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
185 then: 'response has 3 values'
186 cmHandleResponseList.size() == 3
187 and: 'the 1st and 3rd requests were processed successfully'
188 with(cmHandleResponseList.get(0)) {
189 assert it.status == Status.SUCCESS
190 assert it.cmHandle == cmHandleId
192 with(cmHandleResponseList.get(2)) {
193 assert it.status == Status.SUCCESS
194 assert it.cmHandle == cmHandleId
196 and: 'the 2nd request failed with correct error code'
197 with(cmHandleResponseList.get(1)) {
198 assert it.status == Status.FAILURE
199 assert it.cmHandle == cmHandleId
200 assert it.ncmpResponseStatus == CM_HANDLES_NOT_FOUND
201 assert it.errorText == 'cm handle reference(s) not found'
203 then: 'the replace list method is called twice'
204 2 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _)
207 def 'Update alternate id of existing CM Handle.'() {
208 given: 'cm handles request'
209 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
210 and: 'the cm handle per alternate id cache returns a value'
211 mockCmHandleIdPerAlternateId.get(_) >> cmHandleId
212 and: 'a data node found'
213 def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
214 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
215 when: 'cm handle properties is updated'
216 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
217 then: 'the update is delegated to inventory persistence with correct parameters'
218 1 * mockInventoryPersistence.updateCmHandleField(cmHandleId, 'alternate-id', 'alt-1')
219 and: 'one successful registration response'
221 and: 'the response shows success for the given cm handle id'
222 assert response[0].status == Status.SUCCESS
223 assert response[0].cmHandle == cmHandleId
226 def 'Update with rejected alternate id.'() {
227 given: 'cm handles request'
228 def updatedNcmpServiceCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
229 and: 'a data node found'
230 def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
231 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
232 when: 'attempt to update the cm handle'
233 def response = objectUnderTest.updateCmHandleProperties(updatedNcmpServiceCmHandles)
234 then: 'the update is NOT delegated to cps data service'
235 0 * mockCpsDataService.updateNodeLeaves(*_)
236 and: 'the alternate id checker rejects the given cm handle (override default setup behavior)'
237 mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> [cmHandleId]
238 and: 'the response shows a failure for the given cm handle id'
239 assert response[0].status == Status.FAILURE
240 assert response[0].cmHandle == cmHandleId
243 def 'Update CM Handle data producer identifier from #scenario'() {
244 given: 'an existing cm handle with old data producer identifier'
245 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': oldDataProducerIdentifier])
246 and: 'an update request with a new data producer identifier'
247 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'New Data Producer Identifier')
248 and: 'the inventory persistence returns updated yang model'
249 1 * mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'New Data Producer Identifier')
250 when: 'data producer identifier is updated'
251 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
252 then: 'the update node leaves method is invoked once with correct parameters'
253 1 * mockInventoryPersistence.updateCmHandleField('cmHandleId', 'data-producer-identifier', 'New Data Producer Identifier')
254 and: 'LCM event is sent'
255 1 * mockLcmEventProducer.sendLcmEventBatchAsynchronously({cmHandleTransitionPairs ->
256 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'New Data Producer Identifier'
258 where: 'the following scenarios are used'
259 scenario | oldDataProducerIdentifier
260 'null to something' | null
261 'blank to something' | ''
264 def 'Update CM Handle data producer identifier with same value'() {
265 given: 'an existing cm handle with existing data producer identifier'
266 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'same-data-producer-id'])
267 and: 'an update request with the same data producer identifier'
268 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'same-data-producer-id')
269 when: 'data producer identifier is updated'
270 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
271 then: 'the update node leaves method is not invoked'
272 0 * mockCpsDataService.updateNodeLeaves(*_)
273 and: 'No LCM events are sent'
274 0 * mockLcmEventProducer.sendLcmEventBatchAsynchronously(*_)
275 and: 'debug information is logged'
276 def loggingEvent = logger.list[0]
277 assert loggingEvent.level == Level.DEBUG
278 assert loggingEvent.formattedMessage.contains('dataProducerIdentifier for cmHandle cmHandleId is already set to same-data-producer-id')
281 def 'Update CM Handle data producer identifier from existing to new value'() {
282 given: 'an existing cm handle with a data producer identifier'
283 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'oldDataProducerIdentifier'])
284 and: 'an update request with a new data producer identifier'
285 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'newDataProducerIdentifier')
286 and: 'the inventory persistence returns updated yang model'
287 mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'newDataProducerIdentifier')
288 when: 'update data producer identifier is called'
289 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
290 then: 'the update node leaves method is invoked once with correct parameters'
291 1 * mockInventoryPersistence.updateCmHandleField('cmHandleId', 'data-producer-identifier', 'newDataProducerIdentifier')
292 and: 'LCM event is sent'
293 1 * mockLcmEventProducer.sendLcmEventBatchAsynchronously( {cmHandleTransitionPairs ->
294 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'newDataProducerIdentifier'
295 assert cmHandleTransitionPairs[0].currentYangModelCmHandle.dataProducerIdentifier == 'oldDataProducerIdentifier'
299 def 'Update CM Handle data producer identifier with null or blank target identifier'() {
300 given: 'an existing cm handle'
301 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'some existing id'])
302 and: 'an update request with null/blank data producer identifier'
303 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: targetDataProducerIdentifier)
304 when: 'data producer identifier update is attempted'
305 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
306 then: 'the update node leaves method is not invoked'
307 0 * mockCpsDataService.updateNodeLeaves(*_)
308 and: 'No LCM events are sent'
309 0 * mockLcmEventProducer.sendLcmEventBatchAsynchronously(*_)
310 and: 'warning is logged'
311 def lastLoggingEvent = logger.list[0]
312 assert lastLoggingEvent.level == Level.WARN
313 assert lastLoggingEvent.formattedMessage.contains('Ignoring update for cmHandle cmHandleId: target dataProducerIdentifier is null or blank')
314 where: 'the following invalid scenarios are used'
315 scenario | targetDataProducerIdentifier
320 def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
321 def properties = [].withDefault { [:] }
322 expectedPropertiesAfterUpdateAsMap.forEach(property ->
323 property.forEach((key, val) -> {
324 properties.add(['name': key, 'value': val])
330 def createYangModelCmHandle(cmHandleId, dataProducerIdentifier) {
331 new YangModelCmHandle(
333 dmiDataServiceName: 'some-dmi-plugin',
334 dataProducerIdentifier: dataProducerIdentifier,
335 additionalProperties: [],