2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2022-2024 Nordix Foundation
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 org.onap.cps.api.CpsDataService
31 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle
32 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
33 import org.onap.cps.spi.exceptions.DataValidationException
34 import org.onap.cps.spi.model.DataNode
35 import org.onap.cps.spi.model.DataNodeBuilder
36 import org.onap.cps.utils.ContentType
37 import org.onap.cps.utils.JsonObjectMapper
38 import org.slf4j.LoggerFactory
39 import spock.lang.Specification
41 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
42 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
43 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
44 import static org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse.Status
45 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME
46 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
48 class CmHandleRegistrationServicePropertyHandlerSpec extends Specification {
50 def mockInventoryPersistence = Mock(InventoryPersistence)
51 def mockCpsDataService = Mock(CpsDataService)
52 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
53 def mockAlternateIdChecker = Mock(AlternateIdChecker)
55 def objectUnderTest = new CmHandleRegistrationServicePropertyHandler(mockInventoryPersistence, mockCpsDataService, jsonObjectMapper, mockAlternateIdChecker)
56 def logger = Spy(ListAppender<ILoggingEvent>)
59 def setupLogger = ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class))
60 setupLogger.addAppender(logger)
61 setupLogger.setLevel(Level.DEBUG)
63 // Always accept all alternate IDs
64 mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
68 ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class)).detachAndStopAllAppenders()
71 def static cmHandleId = 'myHandle1'
72 def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
74 def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
75 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
76 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
77 new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
78 def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes, leaves: ['id': cmHandleId])]
80 def 'Update CM Handle Public Properties: #scenario'() {
81 given: 'the CPS service return a CM handle'
82 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> cmHandleDataNodeAsCollection
83 and: 'an update cm handle request with public properties updates'
84 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
85 when: 'update data node leaves is called with the update request'
86 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
87 then: 'the replace list method is called with correct params'
88 1 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
90 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
91 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
94 where: 'following public properties updates are made'
95 scenario | updatedPublicProperties || expectedPropertiesAfterUpdate
96 'property added' | ['newPubProp1': 'pub-val'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
97 'property updated' | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
98 'property removed' | ['publicProp4': null] || [['publicProp3': 'publicValue3']]
99 'property ignored(value is null)' | ['pub-prop': null] || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
102 def 'Update DMI Properties: #scenario'() {
103 given: 'the CPS service return a CM handle'
104 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> cmHandleDataNodeAsCollection
105 and: 'an update cm handle request with DMI properties updates'
106 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
107 when: 'update data node leaves is called with the update request'
108 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
109 then: 'replace list method should is called with correct params'
110 expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
112 assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
113 assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
116 where: 'following DMI properties updates are made'
117 scenario | updatedDmiProperties || expectedPropertiesAfterUpdate | expectedCallsToReplaceMethod
118 'property added' | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
119 'property updated' | ['additionalProp1': 'newValue'] || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']] | 1
120 'property removed' | ['additionalProp1': null] || [['additionalProp2': 'additionalValue2']] | 1
121 'property ignored(value is null)' | ['new-prop': null] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 1
122 'no property changes' | [:] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']] | 0
125 def 'Update CM Handle Properties, remove all properties: #scenario'() {
126 given: 'the CPS service return a CM handle'
127 def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId], childDataNodes: originalPropertyDataNodes)
128 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [cmHandleDataNode]
129 and: 'an update cm handle request that removes all public properties(existing and non-existing)'
130 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
131 when: 'update data node leaves is called with the update request'
132 objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
133 then: 'the replace list method is not called'
134 0 * mockInventoryPersistence.replaceListContent(*_)
135 then: 'delete data node will be called for any existing property'
136 expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
138 assert arg[0].contains("@name='publicProp")
141 where: 'following public properties updates are made'
142 scenario | originalPropertyDataNodes || expectedCallsToDeleteDataNode
143 '2 original properties, both removed' | propertyDataNodes || 2
144 'no original properties' | [] || 0
147 def '#scenario error leads to #exception when we try to update cmHandle'() {
148 given: 'cm handles request'
149 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
150 and: 'data node cannot be found'
151 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> { throw exception }
152 when: 'update data node leaves is called using correct parameters'
153 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
154 then: 'one failed registration response'
156 and: 'it has expected error details'
157 with(response.get(0)) {
158 assert it.status == Status.FAILURE
159 assert it.cmHandle == cmHandleId
160 assert it.ncmpResponseStatus == expectedError
161 assert it.errorText == expectedErrorText
164 scenario | cmHandleId | exception || expectedError | expectedErrorText
165 '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'
166 'Unknown' | 'cmHandleId' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
167 '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'
170 def 'Multiple update operations in a single request'() {
171 given: 'cm handles request'
172 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
173 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
174 new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:])]
175 and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
176 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> cmHandleDataNodeAsCollection >> {
177 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
178 when: 'update data node leaves is called using correct parameters'
179 def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
180 then: 'response has 3 values'
181 cmHandleResponseList.size() == 3
182 and: 'the 1st and 3rd requests were processed successfully'
183 with(cmHandleResponseList.get(0)) {
184 assert it.status == Status.SUCCESS
185 assert it.cmHandle == cmHandleId
187 with(cmHandleResponseList.get(2)) {
188 assert it.status == Status.SUCCESS
189 assert it.cmHandle == cmHandleId
191 and: 'the 2nd request failed with correct error code'
192 with(cmHandleResponseList.get(1)) {
193 assert it.status == Status.FAILURE
194 assert it.cmHandle == cmHandleId
195 assert it.ncmpResponseStatus == CM_HANDLES_NOT_FOUND
196 assert it.errorText == 'cm handle reference(s) not found'
198 then: 'the replace list method is called twice'
199 2 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _)
202 def 'Update alternate id of existing CM Handle.'() {
203 given: 'cm handles request'
204 def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
205 and: 'a data node found'
206 def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
207 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [dataNode]
208 when: 'cm handle properties is updated'
209 def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
210 then: 'the update is delegated to cps data service with correct parameters'
211 1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >>
213 assert args[3].contains('alt-1')
215 and: 'one successful registration response'
217 and: 'the response shows success for the given cm handle id'
218 assert response[0].status == Status.SUCCESS
219 assert response[0].cmHandle == cmHandleId
222 def 'Update with rejected alternate id.'() {
223 given: 'cm handles request'
224 def updatedNcmpServiceCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
225 and: 'a data node found'
226 def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
227 mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [dataNode]
228 when: 'attempt to update the cm handle'
229 def response = objectUnderTest.updateCmHandleProperties(updatedNcmpServiceCmHandles)
230 then: 'the update is NOT delegated to cps data service'
231 0 * mockCpsDataService.updateNodeLeaves(*_)
232 and: 'the alternate id checker rejects the given cm handle (override default setup behavior)'
233 mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> [cmHandleId]
234 and: 'the response shows a failure for the given cm handle id'
235 assert response[0].status == Status.FAILURE
236 assert response[0].cmHandle == cmHandleId
239 def 'Update CM Handle data producer identifier from #scenario'() {
240 given: 'an existing cm handle with no data producer identifier'
241 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId','data-producer-identifier': oldDataProducerIdentifier])
242 and: 'an update request with a new data producer identifier'
243 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dataProducerIdentifier: 'New Data Producer Identifier')
244 when: 'data producer identifier updated'
245 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
246 then: 'the update node leaves method is invoked once'
247 1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >> { args ->
248 assert args[3].contains('New Data Producer Identifier')
250 and: 'correct information is logged'
251 def lastLoggingEvent = logger.list[0]
252 assert lastLoggingEvent.level == Level.DEBUG
253 assert lastLoggingEvent.formattedMessage.contains('Updating data-producer-identifier')
254 where: 'the following scenarios are attempted'
255 scenario | oldDataProducerIdentifier
256 'null to something' | null
257 'blank to something' | ''
260 def 'Update CM Handle data producer identifier with same value'() {
261 given: 'an existing cm handle with no data producer identifier'
262 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId','data-producer-identifier': 'same id'])
263 and: 'an update request with a new data producer identifier'
264 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dataProducerIdentifier: 'same id')
265 when: 'data producer identifier updated'
266 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
267 then: 'the update node leaves method is not invoked'
268 0 * mockCpsDataService.updateNodeLeaves(*_)
271 def 'Update CM Handle data producer identifier from some data producer identifier to another data producer identifier'() {
272 given: 'an existing cm handle with a data producer identifier'
273 DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'someDataProducerIdentifier'])
274 and: 'an update request with a new data producer identifier'
275 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dataProducerIdentifier: 'someNewDataProducerIdentifier')
276 when: 'update data producer identifier is called with the update request'
277 objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
278 then: 'the update node leaves method is not invoked'
279 0 * mockCpsDataService.updateNodeLeaves(*_)
280 and: 'correct information is logged'
281 def lastLoggingEvent = logger.list[0]
282 assert lastLoggingEvent.level == Level.WARN
283 assert lastLoggingEvent.formattedMessage.contains('Unable to update dataProducerIdentifier')
286 def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
287 def properties = [].withDefault { [:] }
288 expectedPropertiesAfterUpdateAsMap.forEach(property ->
289 property.forEach((key, val) -> {
290 properties.add(['name': key, 'value': val])