Merge "Define Initial Data Sync Enabled Flag and state"
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServicePropertyHandlerSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2022 Nordix Foundation
4  * Modifications Copyright (C) 2022 Bell Canada
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *       http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl
23
24 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
25 import org.onap.cps.spi.exceptions.DataValidationException
26
27 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
28 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_INVALID_ID
29 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
30 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
31
32 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
33 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
34 import org.onap.cps.spi.model.DataNode
35 import org.onap.cps.spi.model.DataNodeBuilder
36 import spock.lang.Specification
37
38 class NetworkCmProxyDataServicePropertyHandlerSpec extends Specification {
39
40     def mockInventoryPersistence = Mock(InventoryPersistence)
41
42     def objectUnderTest = new NetworkCmProxyDataServicePropertyHandler(mockInventoryPersistence)
43     def static cmHandleId = 'myHandle1'
44     def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
45
46     def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
47                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
48                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
49                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
50     def static cmHandleDataNode = new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes)
51
52     def 'Update CM Handle Public Properties: #scenario'() {
53         given: 'the CPS service return a CM handle'
54             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> cmHandleDataNode
55         and: 'an update cm handle request with public properties updates'
56             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
57         when: 'update data node leaves is called with the update request'
58             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
59         then: 'the replace list method is called with correct params'
60             1 * mockInventoryPersistence.replaceListContent(cmHandleXpath,_) >> { args ->
61                 {
62                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
63                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
64                 }
65             }
66         where: 'following public properties updates are made'
67             scenario                          | updatedPublicProperties      || expectedPropertiesAfterUpdate
68             'property added'                  | ['newPubProp1': 'pub-val']   || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
69             'property updated'                | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
70             'property removed'                | ['publicProp4': null]        || [['publicProp3': 'publicValue3']]
71             'property ignored(value is null)' | ['pub-prop': null]           || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
72     }
73
74     def 'Update DMI Properties: #scenario'() {
75         given: 'the CPS service return a CM handle'
76             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> cmHandleDataNode
77         and: 'an update cm handle request with DMI properties updates'
78             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
79         when: 'update data node leaves is called with the update request'
80             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
81         then: 'replace list method should is called with correct params'
82             expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
83                 {
84                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
85                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
86                 }
87             }
88         where: 'following DMI properties updates are made'
89             scenario                          | updatedDmiProperties                || expectedPropertiesAfterUpdate                                                                                           | expectedCallsToReplaceMethod
90             'property added'                  | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
91             'property updated'                | ['additionalProp1': 'newValue']     || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']]                                              | 1
92             'property removed'                | ['additionalProp1': null]           || [['additionalProp2': 'additionalValue2']]                                                                               | 1
93             'property ignored(value is null)' | ['new-prop': null]                  || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 1
94             'no property changes'             | [:]                                 || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 0
95     }
96
97     def 'Update CM Handle Properties, remove all properties: #scenario'() {
98         given: 'the CPS service return a CM handle'
99             def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, childDataNodes: originalPropertyDataNodes)
100             mockInventoryPersistence.getCmHandleDataNode(cmHandleId) >> cmHandleDataNode
101         and: 'an update cm handle request that removes all public properties(existing and non-existing)'
102             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
103         when: 'update data node leaves is called with the update request'
104             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
105         then: 'the replace list method is not called'
106             0 * mockInventoryPersistence.replaceListContent(*_)
107         then: 'delete data node will be called for any existing property'
108             expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
109                 {
110                     assert arg[0].contains("@name='publicProp")
111                 }
112             }
113         where: 'following public properties updates are made'
114             scenario                              | originalPropertyDataNodes || expectedCallsToDeleteDataNode
115             '2 original properties, both removed' | propertyDataNodes         || 2
116             'no original properties'              | []                        || 0
117     }
118
119     def '#scenario error leads to #exception when we try to update cmHandle'() {
120         given: 'cm handles request'
121             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
122         and: 'data node cannot be found'
123             mockInventoryPersistence.getCmHandleDataNode(*_) >> { throw exception }
124         when: 'update data node leaves is called using correct parameters'
125             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
126         then: 'one failed registration response'
127             response.size() == 1
128         and: 'it has expected error details'
129             with(response.get(0)) {
130                 assert it.status == Status.FAILURE
131                 assert it.cmHandle == cmHandleId
132                 assert it.registrationError == expectedError
133                 assert it.errorText == expectedErrorText
134             }
135         where:
136             scenario                   | cmHandleId               | exception                                                                                           || expectedError            | expectedErrorText
137             'Cm Handle does not exist' | 'cmHandleId'             | new DataNodeNotFoundException('NCMP-Admin', 'ncmp-dmi-registry')                                    || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
138             'Unknown'                  | 'cmHandleId'             | new RuntimeException('Failed')                                                                      || UNKNOWN_ERROR            | 'Failed'
139             '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'
140     }
141
142     def 'Multiple update operations in a single request'() {
143         given: 'cm handles request'
144             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
145                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:]),
146                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], dmiProperties: [:])]
147         and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
148             mockInventoryPersistence.getCmHandleDataNode(*_) >> cmHandleDataNode >> { throw new DataNodeNotFoundException('NCMP-Admin', 'ncmp-dmi-registry') } >> cmHandleDataNode
149         when: 'update data node leaves is called using correct parameters'
150             def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
151         then: 'response has 3 values'
152             cmHandleResponseList.size() == 3
153         and: 'the 1st and 3rd requests were processed successfully'
154             with(cmHandleResponseList.get(0)) {
155                 assert it.status == Status.SUCCESS
156                 assert it.cmHandle == cmHandleId
157             }
158             with(cmHandleResponseList.get(2)) {
159                 assert it.status == Status.SUCCESS
160                 assert it.cmHandle == cmHandleId
161             }
162         and: 'the 2nd request failed with correct error code'
163             with(cmHandleResponseList.get(1)) {
164                 assert it.status == Status.FAILURE
165                 assert it.cmHandle == cmHandleId
166                 assert it.registrationError == CM_HANDLE_DOES_NOT_EXIST
167                 assert it.errorText == "cm-handle does not exist"
168             }
169         then: 'the replace list method is called twice'
170             2 * mockInventoryPersistence.replaceListContent(cmHandleXpath,_)
171     }
172
173     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
174         def properties = [].withDefault { [:] }
175         expectedPropertiesAfterUpdateAsMap.forEach(property ->
176             property.forEach((key, val) -> {
177                 properties.add(['name': key, 'value': val])
178             }))
179         return properties
180     }
181
182 }