610400f75bdede7131fe91dd06ac08b38b736558
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServicePropertyHandlerSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2022-2023 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 static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME
26 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
27
28 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence
29 import org.onap.cps.spi.exceptions.DataValidationException
30 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
31 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_INVALID_ID
32 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
33 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
34 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
35 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
36 import org.onap.cps.spi.model.DataNode
37 import org.onap.cps.spi.model.DataNodeBuilder
38 import spock.lang.Specification
39
40 class NetworkCmProxyDataServicePropertyHandlerSpec extends Specification {
41
42     def mockInventoryPersistence = Mock(InventoryPersistence)
43
44     def objectUnderTest = new NetworkCmProxyDataServicePropertyHandler(mockInventoryPersistence)
45     def static cmHandleId = 'myHandle1'
46     def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
47
48     def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
49                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
50                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
51                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
52     def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes)]
53
54     def 'Update CM Handle Public Properties: #scenario'() {
55         given: 'the CPS service return a CM handle'
56             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> cmHandleDataNodeAsCollection
57         and: 'an update cm handle request with public properties updates'
58             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
59         when: 'update data node leaves is called with the update request'
60             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
61         then: 'the replace list method is called with correct params'
62             1 * mockInventoryPersistence.replaceListContent(cmHandleXpath,_) >> { args ->
63                 {
64                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
65                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
66                 }
67             }
68         where: 'following public properties updates are made'
69             scenario                          | updatedPublicProperties      || expectedPropertiesAfterUpdate
70             'property added'                  | ['newPubProp1': 'pub-val']   || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
71             'property updated'                | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
72             'property removed'                | ['publicProp4': null]        || [['publicProp3': 'publicValue3']]
73             'property ignored(value is null)' | ['pub-prop': null]           || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
74     }
75
76     def 'Update DMI Properties: #scenario'() {
77         given: 'the CPS service return a CM handle'
78             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> cmHandleDataNodeAsCollection
79         and: 'an update cm handle request with DMI properties updates'
80             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
81         when: 'update data node leaves is called with the update request'
82             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
83         then: 'replace list method should is called with correct params'
84             expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
85                 {
86                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
87                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
88                 }
89             }
90         where: 'following DMI properties updates are made'
91             scenario                          | updatedDmiProperties                || expectedPropertiesAfterUpdate                                                                                           | expectedCallsToReplaceMethod
92             'property added'                  | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
93             'property updated'                | ['additionalProp1': 'newValue']     || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']]                                              | 1
94             'property removed'                | ['additionalProp1': null]           || [['additionalProp2': 'additionalValue2']]                                                                               | 1
95             'property ignored(value is null)' | ['new-prop': null]                  || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 1
96             'no property changes'             | [:]                                 || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 0
97     }
98
99     def 'Update CM Handle Properties, remove all properties: #scenario'() {
100         given: 'the CPS service return a CM handle'
101             def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, childDataNodes: originalPropertyDataNodes)
102             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> [cmHandleDataNode]
103         and: 'an update cm handle request that removes all public properties(existing and non-existing)'
104             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
105         when: 'update data node leaves is called with the update request'
106             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
107         then: 'the replace list method is not called'
108             0 * mockInventoryPersistence.replaceListContent(*_)
109         then: 'delete data node will be called for any existing property'
110             expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
111                 {
112                     assert arg[0].contains("@name='publicProp")
113                 }
114             }
115         where: 'following public properties updates are made'
116             scenario                              | originalPropertyDataNodes || expectedCallsToDeleteDataNode
117             '2 original properties, both removed' | propertyDataNodes         || 2
118             'no original properties'              | []                        || 0
119     }
120
121     def '#scenario error leads to #exception when we try to update cmHandle'() {
122         given: 'cm handles request'
123             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
124         and: 'data node cannot be found'
125             mockInventoryPersistence.getCmHandleDataNode(*_) >> { throw exception }
126         when: 'update data node leaves is called using correct parameters'
127             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
128         then: 'one failed registration response'
129             response.size() == 1
130         and: 'it has expected error details'
131             with(response.get(0)) {
132                 assert it.status == Status.FAILURE
133                 assert it.cmHandle == cmHandleId
134                 assert it.registrationError == expectedError
135                 assert it.errorText == expectedErrorText
136             }
137         where:
138             scenario                   | cmHandleId               | exception                                                                                           || expectedError            | expectedErrorText
139             'Cm Handle does not exist' | 'cmHandleId'             | new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR)                                    || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
140             'Unknown'                  | 'cmHandleId'             | new RuntimeException('Failed')                                                                      || UNKNOWN_ERROR            | 'Failed'
141             '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'
142     }
143
144     def 'Multiple update operations in a single request'() {
145         given: 'cm handles request'
146             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
147                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
148                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:])]
149         and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
150             mockInventoryPersistence.getCmHandleDataNode(*_) >> cmHandleDataNodeAsCollection >> {
151                 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
152         when: 'update data node leaves is called using correct parameters'
153             def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
154         then: 'response has 3 values'
155             cmHandleResponseList.size() == 3
156         and: 'the 1st and 3rd requests were processed successfully'
157             with(cmHandleResponseList.get(0)) {
158                 assert it.status == Status.SUCCESS
159                 assert it.cmHandle == cmHandleId
160             }
161             with(cmHandleResponseList.get(2)) {
162                 assert it.status == Status.SUCCESS
163                 assert it.cmHandle == cmHandleId
164             }
165         and: 'the 2nd request failed with correct error code'
166             with(cmHandleResponseList.get(1)) {
167                 assert it.status == Status.FAILURE
168                 assert it.cmHandle == cmHandleId
169                 assert it.registrationError == CM_HANDLE_DOES_NOT_EXIST
170                 assert it.errorText == "cm-handle does not exist"
171             }
172         then: 'the replace list method is called twice'
173             2 * mockInventoryPersistence.replaceListContent(cmHandleXpath,_)
174     }
175
176     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
177         def properties = [].withDefault { [:] }
178         expectedPropertiesAfterUpdateAsMap.forEach(property ->
179             property.forEach((key, val) -> {
180                 properties.add(['name': key, 'value': val])
181             }))
182         return properties
183     }
184
185 }