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