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