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