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.ncmp.api.inventory.models.NcmpServiceCmHandle
33 import org.onap.cps.api.exceptions.DataNodeNotFoundException
34 import org.onap.cps.api.exceptions.DataValidationException
35 import org.onap.cps.api.model.DataNode
36 import org.onap.cps.impl.DataNodeBuilder
37 import org.onap.cps.utils.ContentType
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.slf4j.LoggerFactory
40 import spock.lang.Specification
42 import static org.onap.cps.api.parameters.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
43 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
44 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
45 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
46 import static org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse.Status
47 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME
48 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
50 class CmHandleRegistrationServicePropertyHandlerSpec extends Specification {
52 def mockInventoryPersistence = Mock(InventoryPersistence)
53 def mockCpsDataService = Mock(CpsDataService)
54 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
55 def mockAlternateIdChecker = Mock(AlternateIdChecker)
56 def mockCmHandleIdPerAlternateId = Mock(IMap)
58 def objectUnderTest = new CmHandleRegistrationServicePropertyHandler(mockInventoryPersistence, mockCpsDataService, jsonObjectMapper, mockAlternateIdChecker, mockCmHandleIdPerAlternateId)
59 def logger = Spy(ListAppender<ILoggingEvent>)
62 def setupLogger = ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class))
63 setupLogger.addAppender(logger)
64 setupLogger.setLevel(Level.DEBUG)
66 // Always accept all alternate IDs
67 mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
71 ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class)).detachAndStopAllAppenders()
74 def static cmHandleId = 'myHandle1'
75 def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
77 def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
78 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
79 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
80 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
81 def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes, leaves: ['id': cmHandleId])]
83 def 'Update CM Handle Public Properties: #scenario'() {
84 given: 'the CPS service return a CM handle'
85 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
86 and: 'an update cm handle request with public properties updates'
87 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
88 when: 'update data node leaves is called with the update request'
89 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
90 then: 'the replace list method is called with correct params'
91 1 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
93 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
94 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
97 where: 'following public properties updates are made'
98 scenario | updatedPublicProperties || expectedPropertiesAfterUpdate
99 'property added' | ['newPubProp1': 'pub-val'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
100 'property updated' | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
101 'property removed' | ['publicProp4': null] || [['publicProp3': 'publicValue3']]
102 'property ignored(value is null)' | ['pub-prop': null] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
105 def 'Update DMI Properties: #scenario'() {
106 given: 'the CPS service return a CM handle'
107 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
108 and: 'an update cm handle request with DMI properties updates'
109 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
110 when: 'update data node leaves is called with the update request'
111 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
112 then: 'replace list method should is called with correct params'
113 expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
115 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
116 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
119 where: 'following DMI properties updates are made'
120 scenario | updatedDmiProperties || expectedPropertiesAfterUpdate | expectedCallsToReplaceMethod
121 'property added' | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
122 'property updated' | ['additionalProp1': 'newValue'] || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']] | 1
123 'property removed' | ['additionalProp1': null] || [['additionalProp2': 'additionalValue2']] | 1
124 'property ignored(value is null)' | ['new-prop': null] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 1
125 'no property changes' | [:] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 0
128 def 'Update CM Handle Properties, remove all properties: #scenario'() {
129 given: 'the CPS service return a CM handle'
130 def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId], childDataNodes: originalPropertyDataNodes)
131 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [cmHandleDataNode]
132 and: 'an update cm handle request that removes all public properties(existing and non-existing)'
133 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
134 when: 'update data node leaves is called with the update request'
135 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
136 then: 'the replace list method is not called'
137 0 * mockInventoryPersistence.replaceListContent(*_)
138 then: 'delete data node will be called for any existing property'
139 expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
141 assert arg[0].contains("@name='publicProp")
144 where: 'following public properties updates are made'
145 scenario | originalPropertyDataNodes || expectedCallsToDeleteDataNode
146 '2 original properties, both removed' | propertyDataNodes || 2
147 'no original properties' | [] || 0
150 def '#scenario error leads to #exception when we try to update cmHandle'() {
151 given: 'cm handles request'
152 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
153 and: 'data node cannot be found'
154 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> { throw exception }
155 when: 'update data node leaves is called using correct parameters'
156 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
157 then: 'one failed registration response'
159 and: 'it has expected error details'
160 with(response.get(0)) {
161 assert it.status == Status.FAILURE
162 assert it.cmHandle == cmHandleId
163 assert it.ncmpResponseStatus == expectedError
164 assert it.errorText == expectedErrorText
167 scenario | cmHandleId | exception || expectedError | expectedErrorText
168 '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'
169 'Unknown' | 'cmHandleId' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
170 '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'
173 def 'Multiple update operations in a single request'() {
174 given: 'cm handles request'
175 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
176 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
177 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:])]
178 and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
179 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> cmHandleDataNodeAsCollection >> {
180 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
181 when: 'update data node leaves is called using correct parameters'
182 def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
183 then: 'response has 3 values'
184 cmHandleResponseList.size() == 3
185 and: 'the 1st and 3rd requests were processed successfully'
186 with(cmHandleResponseList.get(0)) {
187 assert it.status == Status.SUCCESS
188 assert it.cmHandle == cmHandleId
190 with(cmHandleResponseList.get(2)) {
191 assert it.status == Status.SUCCESS
192 assert it.cmHandle == cmHandleId
194 and: 'the 2nd request failed with correct error code'
195 with(cmHandleResponseList.get(1)) {
196 assert it.status == Status.FAILURE
197 assert it.cmHandle == cmHandleId
198 assert it.ncmpResponseStatus == CM_HANDLES_NOT_FOUND
199 assert it.errorText == 'cm handle reference(s) not found'
201 then: 'the replace list method is called twice'
202 2 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _)
205 def 'Update alternate id of existing CM Handle.'() {
206 given: 'cm handles request'
207 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
208 and: 'the cm handle per alternate id cache returns a value'
209 mockCmHandleIdPerAlternateId.get(_) >> 'someId'
210 and: 'a data node found'
211 def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
212 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
213 when: 'cm handle properties is updated'
214 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
215 then: 'the update is delegated to cps data service with correct parameters'
216 1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >>
218 assert args[3].contains('alt-1')
220 and: 'one successful registration response'
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
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
244 def 'Update CM Handle data producer identifier from #scenario'() {
245 given: 'an existing cm handle with no 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 when: 'data producer identifier updated'
250 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
251 then: 'the update node leaves method is invoked once'
252 1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >> { args ->
253 assert args[3].contains('New Data Producer Identifier')
255 and: 'correct information is logged'
256 def lastLoggingEvent = logger.list[0]
257 assert lastLoggingEvent.level == Level.DEBUG
258 assert lastLoggingEvent.formattedMessage.contains('Updating data-producer-identifier')
259 where: 'the following scenarios are attempted'
260 scenario | oldDataProducerIdentifier
261 'null to something' | null
262 'blank to something' | ''
265 def 'Update CM Handle data producer identifier with same value'() {
266 given: 'an existing cm handle with no data producer identifier'
267 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId','data-producer-identifier': 'same id'])
268 and: 'an update request with a new data producer identifier'
269 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dataProducerIdentifier: 'same id')
270 when: 'data producer identifier updated'
271 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
272 then: 'the update node leaves method is not invoked'
273 0 * mockCpsDataService.updateNodeLeaves(*_)
276 def 'Update CM Handle data producer identifier from some data producer identifier to another data producer identifier'() {
277 given: 'an existing cm handle with a data producer identifier'
278 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'someDataProducerIdentifier'])
279 and: 'an update request with a new data producer identifier'
280 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dataProducerIdentifier: 'someNewDataProducerIdentifier')
281 when: 'update data producer identifier is called with the update request'
282 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
283 then: 'the update node leaves method is not invoked'
284 0 * mockCpsDataService.updateNodeLeaves(*_)
285 and: 'correct information is logged'
286 def lastLoggingEvent = logger.list[0]
287 assert lastLoggingEvent.level == Level.WARN
288 assert lastLoggingEvent.formattedMessage.contains('Unable to update dataProducerIdentifier')
291 def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
292 def properties = [].withDefault { [:] }
293 expectedPropertiesAfterUpdateAsMap.forEach(property ->
294 property.forEach((key, val) -> {
295 properties.add(['name': key, 'value': val])