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