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