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