Merge "Publish LCM Events"
[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.impl.event.NcmpEventsService
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 import static org.onap.ncmp.cmhandle.lcm.event.Event.Operation.UPDATE
32
33 import org.onap.cps.api.CpsDataService
34 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
35 import org.onap.cps.spi.FetchDescendantsOption
36 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
37 import org.onap.cps.spi.model.DataNode
38 import org.onap.cps.spi.model.DataNodeBuilder
39 import spock.lang.Specification
40
41 class NetworkCmProxyDataServicePropertyHandlerSpec extends Specification {
42
43     def mockCpsDataService = Mock(CpsDataService)
44     def mockNcmpEventsService = Mock(NcmpEventsService)
45
46     def objectUnderTest = new NetworkCmProxyDataServicePropertyHandler(mockCpsDataService, mockNcmpEventsService)
47     def dataspaceName = 'NCMP-Admin'
48     def anchorName = 'ncmp-dmi-registry'
49     def static cmHandleId = 'myHandle1'
50     def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
51     def noTimeStamp = null
52
53     def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
54                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
55                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
56                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
57     def static cmHandleDataNode = new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes)
58
59     def 'Update CM Handle Public Properties: #scenario'() {
60         given: 'the CPS service return a CM handle'
61             mockCpsDataService.getDataNode(dataspaceName, anchorName, cmHandleXpath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
62         and: 'an update cm handle request with public properties updates'
63             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
64         when: 'update data node leaves is called with the update request'
65             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
66         then: 'the replace list method is called with correct params'
67             1 * mockCpsDataService.replaceListContent(dataspaceName, anchorName, cmHandleXpath, _, noTimeStamp) >> { args ->
68                 {
69                     assert args[3].leaves.size() == expectedPropertiesAfterUpdate.size()
70                     assert args[3].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
71                 }
72             }
73         and: 'ncmp event is published'
74             1 * mockNcmpEventsService.publishNcmpEvent(cmHandleId, UPDATE)
75         where: 'following public properties updates are made'
76             scenario                          | updatedPublicProperties      || expectedPropertiesAfterUpdate
77             'property added'                  | ['newPubProp1': 'pub-val']   || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
78             'property updated'                | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
79             'property removed'                | ['publicProp4': null]        || [['publicProp3': 'publicValue3']]
80             'property ignored(value is null)' | ['pub-prop': null]           || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
81     }
82
83     def 'Update DMI Properties: #scenario'() {
84         given: 'the CPS service return a CM handle'
85             mockCpsDataService.getDataNode(dataspaceName, anchorName, cmHandleXpath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNode
86         and: 'an update cm handle request with DMI properties updates'
87             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: updatedDmiProperties)]
88         when: 'update data node leaves is called with the update request'
89             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
90         then: 'replace list method should is called with correct params'
91             expectedCallsToReplaceMethod * mockCpsDataService.replaceListContent(dataspaceName, anchorName, cmHandleXpath, _, noTimeStamp) >> { args ->
92                 {
93                     assert args[3].leaves.size() == expectedPropertiesAfterUpdate.size()
94                     assert args[3].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
95                 }
96             }
97         and: 'ncmp event is not published on dmi properties update'
98             0 * mockNcmpEventsService.publishNcmpEvent(_, _)
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             mockCpsDataService.getDataNode(dataspaceName, anchorName, cmHandleXpath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> 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 * mockCpsDataService.replaceListContent(*_)
118         then: 'delete data node will be called for any existing property'
119             expectedCallsToDeleteDataNode * mockCpsDataService.deleteDataNode(dataspaceName, anchorName, _, noTimeStamp) >> { arg ->
120                 {
121                     assert arg[2].contains("@name='publicProp")
122                 }
123             }
124         and: 'ncmp event is published with updated public properties'
125             1 * mockNcmpEventsService.publishNcmpEvent(cmHandleId, UPDATE)
126         where: 'following public properties updates are made'
127             scenario                              | originalPropertyDataNodes || expectedCallsToDeleteDataNode
128             '2 original properties, both removed' | propertyDataNodes         || 2
129             'no original properties'              | []                        || 0
130     }
131
132     def '#scenario error leads to #exception when we try to update cmHandle'() {
133         given: 'cm handles request'
134             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], dmiProperties: [:])]
135         and: 'data node cannot be found'
136             mockCpsDataService.getDataNode(*_) >> { throw exception }
137         when: 'update data node leaves is called using correct parameters'
138             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
139         then: 'one failed registration response'
140             response.size() == 1
141         and: 'it has expected error details'
142             with(response.get(0)) {
143                 assert it.status == Status.FAILURE
144                 assert it.cmHandle == cmHandleId
145                 assert it.registrationError == expectedError
146                 assert it.errorText == expectedErrorText
147             }
148         and: 'ncmp event is not published'
149             0 * mockNcmpEventsService.publishNcmpEvent(_, _)
150         where:
151             scenario                   | cmHandleId               | exception                                                                                           || expectedError            | expectedErrorText
152             'Cm Handle does not exist' | 'cmHandleId'             | new DataNodeNotFoundException('NCMP-Admin', 'ncmp-dmi-registry')                                    || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
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             mockCpsDataService.getDataNode(*_) >> cmHandleDataNode >> { throw new DataNodeNotFoundException('NCMP-Admin', 'ncmp-dmi-registry') } >> cmHandleDataNode
164         when: 'update data node leaves is called using correct parameters'
165             def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
166         then: 'response has 3 values'
167             cmHandleResponseList.size() == 3
168         and: 'the 1st and 3rd requests were processed successfully'
169             with(cmHandleResponseList.get(0)) {
170                 assert it.status == Status.SUCCESS
171                 assert it.cmHandle == cmHandleId
172             }
173             with(cmHandleResponseList.get(2)) {
174                 assert it.status == Status.SUCCESS
175                 assert it.cmHandle == cmHandleId
176             }
177         and: 'the 2nd request failed with correct error code'
178             with(cmHandleResponseList.get(1)) {
179                 assert it.status == Status.FAILURE
180                 assert it.cmHandle == cmHandleId
181                 assert it.registrationError == CM_HANDLE_DOES_NOT_EXIST
182                 assert it.errorText == "cm-handle does not exist"
183             }
184         then: 'the replace list method is called twice'
185             2 * mockCpsDataService.replaceListContent(dataspaceName, anchorName, cmHandleXpath, _, noTimeStamp)
186         and: 'the ncmp event is published'
187             2 * mockNcmpEventsService.publishNcmpEvent(cmHandleId, UPDATE)
188     }
189
190     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
191         def properties = [].withDefault { [:] }
192         expectedPropertiesAfterUpdateAsMap.forEach(property ->
193             property.forEach((key, val) -> {
194                 properties.add(['name': key, 'value': val])
195             }))
196         return properties
197     }
198
199 }