Error reporting when registering cm handle with alternate id 2 - update scenario
[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) 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
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 com.fasterxml.jackson.databind.ObjectMapper
26 import org.onap.cps.api.CpsDataService
27 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence
28 import org.onap.cps.ncmp.api.impl.utils.AlternateIdChecker
29 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
30 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
31 import org.onap.cps.spi.exceptions.DataValidationException
32 import org.onap.cps.spi.model.DataNode
33 import org.onap.cps.spi.model.DataNodeBuilder
34 import org.onap.cps.utils.JsonObjectMapper
35 import spock.lang.Specification
36
37 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
38 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
39 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
40 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME
41 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
42 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
43
44 class NetworkCmProxyDataServicePropertyHandlerSpec extends Specification {
45
46     def mockInventoryPersistence = Mock(InventoryPersistence)
47     def mockCpsDataService = Mock(CpsDataService)
48     def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
49     def mockAlternateIdChecker = Mock(AlternateIdChecker)
50
51     def objectUnderTest = new NetworkCmProxyDataServicePropertyHandler(mockInventoryPersistence, mockCpsDataService, jsonObjectMapper, mockAlternateIdChecker)
52
53     def setup() {
54         // Always accept all alternate IDs
55         mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
56     }
57
58     def static cmHandleId = 'myHandle1'
59     def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
60
61     def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
62                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
63                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
64                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
65     def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes, leaves: ['id': cmHandleId])]
66
67     def 'Update CM Handle Public Properties: #scenario'() {
68         given: 'the CPS service return a CM handle'
69             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> cmHandleDataNodeAsCollection
70         and: 'an update cm handle request with public properties updates'
71             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
72         when: 'update data node leaves is called with the update request'
73             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
74         then: 'the replace list method is called with correct params'
75             1 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
76                 {
77                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
78                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
79                 }
80             }
81         where: 'following public properties updates are made'
82             scenario                          | updatedPublicProperties      || expectedPropertiesAfterUpdate
83             'property added'                  | ['newPubProp1': 'pub-val']   || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
84             'property updated'                | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
85             'property removed'                | ['publicProp4': null]        || [['publicProp3': 'publicValue3']]
86             'property ignored(value is null)' | ['pub-prop': null]           || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
87     }
88
89     def 'Update DMI Properties: #scenario'() {
90         given: 'the CPS service return a CM handle'
91             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> cmHandleDataNodeAsCollection
92         and: 'an update cm handle request with DMI properties updates'
93             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
94         when: 'update data node leaves is called with the update request'
95             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
96         then: 'replace list method should is called with correct params'
97             expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
98                 {
99                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
100                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
101                 }
102             }
103         where: 'following DMI properties updates are made'
104             scenario                          | updatedDmiProperties                || expectedPropertiesAfterUpdate                                                                                           | expectedCallsToReplaceMethod
105             'property added'                  | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
106             'property updated'                | ['additionalProp1': 'newValue']     || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']]                                              | 1
107             'property removed'                | ['additionalProp1': null]           || [['additionalProp2': 'additionalValue2']]                                                                               | 1
108             'property ignored(value is null)' | ['new-prop': null]                  || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 1
109             'no property changes'             | [:]                                 || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 0
110     }
111
112     def 'Update CM Handle Properties, remove all properties: #scenario'() {
113         given: 'the CPS service return a CM handle'
114             def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId], childDataNodes: originalPropertyDataNodes)
115             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [cmHandleDataNode]
116         and: 'an update cm handle request that removes all public properties(existing and non-existing)'
117             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
118         when: 'update data node leaves is called with the update request'
119             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
120         then: 'the replace list method is not called'
121             0 * mockInventoryPersistence.replaceListContent(*_)
122         then: 'delete data node will be called for any existing property'
123             expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
124                 {
125                     assert arg[0].contains("@name='publicProp")
126                 }
127             }
128         where: 'following public properties updates are made'
129             scenario                              | originalPropertyDataNodes || expectedCallsToDeleteDataNode
130             '2 original properties, both removed' | propertyDataNodes         || 2
131             'no original properties'              | []                        || 0
132     }
133
134     def '#scenario error leads to #exception when we try to update cmHandle'() {
135         given: 'cm handles request'
136             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
137         and: 'data node cannot be found'
138             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> { throw exception }
139         when: 'update data node leaves is called using correct parameters'
140             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
141         then: 'one failed registration response'
142             response.size() == 1
143         and: 'it has expected error details'
144             with(response.get(0)) {
145                 assert it.status == Status.FAILURE
146                 assert it.cmHandle == cmHandleId
147                 assert it.ncmpResponseStatus == expectedError
148                 assert it.errorText == expectedErrorText
149             }
150         where:
151             scenario                   | cmHandleId               | exception                                                                                           || expectedError        | expectedErrorText
152             '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'
153             'Unknown'                  | 'cmHandleId'             | new RuntimeException('Failed')                                                                      || UNKNOWN_ERROR        | 'Failed'
154             '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'
155     }
156
157     def 'Multiple update operations in a single request'() {
158         given: 'cm handles request'
159             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
160                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
161                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:])]
162         and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
163             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> cmHandleDataNodeAsCollection >> {
164                 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
165         when: 'update data node leaves is called using correct parameters'
166             def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
167         then: 'response has 3 values'
168             cmHandleResponseList.size() == 3
169         and: 'the 1st and 3rd requests were processed successfully'
170             with(cmHandleResponseList.get(0)) {
171                 assert it.status == Status.SUCCESS
172                 assert it.cmHandle == cmHandleId
173             }
174             with(cmHandleResponseList.get(2)) {
175                 assert it.status == Status.SUCCESS
176                 assert it.cmHandle == cmHandleId
177             }
178         and: 'the 2nd request failed with correct error code'
179             with(cmHandleResponseList.get(1)) {
180                 assert it.status == Status.FAILURE
181                 assert it.cmHandle == cmHandleId
182                 assert it.ncmpResponseStatus == CM_HANDLES_NOT_FOUND
183                 assert it.errorText == 'cm handle id(s) not found'
184             }
185         then: 'the replace list method is called twice'
186             2 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _)
187     }
188
189     def 'Update alternate id of existing CM Handle.'() {
190         given: 'cm handles request'
191             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
192         and: 'a data node found'
193             def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
194             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [dataNode]
195         when: 'cm handle properties is updated'
196             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
197         then: 'the update is delegated to cps data service with correct parameters'
198             1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _) >>
199                     { args ->
200                         assert args[3].contains('alt-1')
201                     }
202         and: 'one successful registration response'
203             response.size() == 1
204         and: 'the response shows success for the given cm handle id'
205                 assert response[0].status == Status.SUCCESS
206                 assert response[0].cmHandle == cmHandleId
207     }
208
209     def 'Update with rejected alternate id.'() {
210         given: 'cm handles request'
211             def updatedNcmpServiceCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
212         and: 'a data node found'
213             def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
214             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId) >> [dataNode]
215         when: 'attempt to update the cm handle'
216             def response = objectUnderTest.updateCmHandleProperties(updatedNcmpServiceCmHandles)
217         then: 'the update is NOT delegated to cps data service'
218             0 * mockCpsDataService.updateNodeLeaves(*_)
219         and:  'the alternate id checker rejects the given cm handle (override default setup behavior)'
220             mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> [cmHandleId]
221         and: 'the response shows a failure for the given cm handle id'
222             assert response[0].status == Status.FAILURE
223             assert response[0].cmHandle == cmHandleId
224     }
225
226     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
227         def properties = [].withDefault { [:] }
228         expectedPropertiesAfterUpdateAsMap.forEach(property ->
229             property.forEach((key, val) -> {
230                 properties.add(['name': key, 'value': val])
231             }))
232         return properties
233     }
234 }