2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2022-2025 OpenInfra Foundation Europe. All rights reserved.
4 * Modifications Copyright (C) 2022 Bell Canada
5 * Modifications Copyright (C) 2024 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.impl.inventory
25 import com.fasterxml.jackson.databind.ObjectMapper
26 import java.time.OffsetDateTime
27 import java.time.ZoneOffset
28 import java.time.format.DateTimeFormatter
29 import org.onap.cps.api.CpsAnchorService
30 import org.onap.cps.api.CpsDataService
31 import org.onap.cps.api.CpsModuleService
32 import org.onap.cps.api.exceptions.DataNodeNotFoundException
33 import org.onap.cps.api.exceptions.DataValidationException
34 import org.onap.cps.api.model.DataNode
35 import org.onap.cps.api.model.ModuleDefinition
36 import org.onap.cps.api.model.ModuleReference
37 import org.onap.cps.utils.CpsValidator
38 import org.onap.cps.ncmp.api.inventory.models.CompositeState
39 import org.onap.cps.ncmp.api.inventory.models.CmHandleState
40 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
41 import org.onap.cps.utils.ContentType
42 import org.onap.cps.utils.JsonObjectMapper
43 import spock.lang.Shared
44 import spock.lang.Specification
46 import static org.onap.cps.api.parameters.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
47 import static org.onap.cps.api.parameters.FetchDescendantsOption.OMIT_DESCENDANTS
48 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME
49 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
50 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT
51 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME
52 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NO_TIMESTAMP
54 class InventoryPersistenceImplSpec extends Specification {
56 def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
58 def mockCpsDataService = Mock(CpsDataService)
60 def mockCpsModuleService = Mock(CpsModuleService)
62 def mockCpsAnchorService = Mock(CpsAnchorService)
64 def mockCpsValidator = Mock(CpsValidator)
66 def objectUnderTest = new InventoryPersistenceImpl(mockCpsValidator, spiedJsonObjectMapper, mockCpsAnchorService, mockCpsModuleService, mockCpsDataService)
68 def formattedDateAndTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
69 .format(OffsetDateTime.of(2022, 12, 31, 20, 30, 40, 1, ZoneOffset.UTC))
71 def cmHandleId = 'some-cm-handle'
72 def alternateId = 'some-alternate-id'
73 def leaves = ["id":cmHandleId, "alternateId":alternateId,"dmi-service-name":"common service name","dmi-data-service-name":"data service name","dmi-model-service-name":"model service name"]
74 def xpath = "/dmi-registry/cm-handles[@id='some-cm-handle']"
76 def cmHandleId2 = 'another-cm-handle'
77 def alternateId2 = 'another-alternate-id'
78 def xpath2 = "/dmi-registry/cm-handles[@id='another-cm-handle']"
80 def dataNode = new DataNode(xpath: "/dmi-registry/cm-handles[@id='some cm handle']/additional-properties[@name='myAdditionalProperty']", leaves: leaves)
83 def childDataNodesForCmHandleWithAllProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some cm handle']/additional-properties[@name='myAdditionalProperty']", leaves: ["name":"myAdditionalProperty", "value":"myAdditionalValue"]),
84 new DataNode(xpath: "/dmi-registry/cm-handles[@id='some cm handle']/public-properties[@name='myPublicProperty']", leaves: ["name":"myPublicProperty","value":"myPublicValue"])]
87 def childDataNodesForCmHandleWithDMIProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some-cm-handle']/additional-properties[@name='myAdditionalProperty']", leaves: ["name":"myAdditionalProperty", "value":"myAdditionalValue"])]
90 def childDataNodesForCmHandleWithPublicProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some-cm-handle']/public-properties[@name='myPublicProperty']", leaves: ["name":"myPublicProperty","value":"myPublicValue"])]
93 def childDataNodesForCmHandleWithState = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some-cm-handle']/state", leaves: ['cm-handle-state': 'ADVISED'])]
95 def 'Retrieve CmHandle using datanode with #scenario.'() {
96 given: 'the cps data service returns a data node from the DMI registry'
97 def dataNode = new DataNode(childDataNodes:childDataNodes, leaves: leaves)
98 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
99 when: 'retrieving the yang modelled cm handle'
100 def result = objectUnderTest.getYangModelCmHandle(cmHandleId)
101 then: 'the result has the correct id and service names'
102 result.id == cmHandleId
103 result.dmiServiceName == 'common service name'
104 result.dmiDataServiceName == 'data service name'
105 result.dmiModelServiceName == 'model service name'
106 and: 'the expected additional properties'
107 result.dmiProperties.name == expectedAdditionalProperties
108 and: 'the expected public properties'
109 result.publicProperties.name == expectedPublicProperties
110 and: 'the state details are returned'
111 result.compositeState.cmHandleState == expectedCompositeState
112 and: 'the CM Handle ID is validated'
113 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
114 where: 'the following parameters are used'
115 scenario | childDataNodes || expectedAdditionalProperties || expectedPublicProperties || expectedCompositeState
116 'no properties' | [] || [] || [] || null
117 'DMI and public properties' | childDataNodesForCmHandleWithAllProperties || ["myAdditionalProperty"] || ["myPublicProperty"] || null
118 'just DMI properties' | childDataNodesForCmHandleWithDMIProperties || ["myAdditionalProperty"] || [] || null
119 'just public properties' | childDataNodesForCmHandleWithPublicProperties || [] || ["myPublicProperty"] || null
120 'with state details' | childDataNodesForCmHandleWithState || [] || [] || CmHandleState.ADVISED
123 def 'Handling missing service names as null.'() {
124 given: 'the cps data service returns a data node from the DMI registry with empty child and leaf attributes'
125 def dataNode = new DataNode(childDataNodes:[], leaves: ['id':cmHandleId])
126 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
127 when: 'retrieving the yang modelled cm handle'
128 def result = objectUnderTest.getYangModelCmHandle(cmHandleId)
129 then: 'the service names are returned as null'
130 result.dmiServiceName == null
131 result.dmiDataServiceName == null
132 result.dmiModelServiceName == null
133 and: 'the CM Handle ID is validated'
134 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
137 def 'Retrieve multiple YangModelCmHandles using cm handle ids'() {
138 given: 'the cps data service returns 2 data nodes from the DMI registry'
139 def dataNodes = [new DataNode(xpath: xpath, leaves: ['id': cmHandleId]), new DataNode(xpath: xpath2, leaves: ['id': cmHandleId2])]
140 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, [xpath, xpath2] , INCLUDE_ALL_DESCENDANTS) >> dataNodes
141 when: 'retrieving the yang modelled cm handles'
142 def results = objectUnderTest.getYangModelCmHandles([cmHandleId, cmHandleId2])
143 then: 'verify both have returned and cm handle Ids are correct'
144 assert results.size() == 2
145 assert results.id.containsAll([cmHandleId, cmHandleId2])
148 def 'YangModelCmHandles are not returned for invalid cm handle ids'() {
149 given: 'invalid cm handle id throws a data validation exception'
150 mockCpsValidator.validateNameCharacters('Invalid Cm Handle Id') >> {throw new DataValidationException('','')}
151 and: 'empty collection is returned as no valid cm handle ids are given'
152 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, [] , INCLUDE_ALL_DESCENDANTS) >> []
153 when: 'retrieving the yang modelled cm handles'
154 def results = objectUnderTest.getYangModelCmHandles(['Invalid Cm Handle Id'])
155 then: 'no YangModelCmHandle is returned'
156 assert results.size() == 0
159 def 'Get a Cm Handle Composite State'() {
160 given: 'a valid cm handle id'
161 def cmHandleId = 'Some-Cm-Handle'
162 def dataNode = new DataNode(leaves: ['cm-handle-state': 'ADVISED'])
163 and: 'cps data service returns a valid data node'
164 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
165 '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle\']/state', INCLUDE_ALL_DESCENDANTS) >> [dataNode]
166 when: 'get cm handle state is invoked'
167 def result = objectUnderTest.getCmHandleState(cmHandleId)
168 then: 'result has returned the correct cm handle state'
169 result.cmHandleState == CmHandleState.ADVISED
170 and: 'the CM Handle ID is validated'
171 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
174 def 'Update Cm Handle with #scenario State'() {
175 given: 'a cm handle and a composite state'
176 def cmHandleId = 'Some-Cm-Handle'
177 def compositeState = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
178 when: 'update cm handle state is invoked with the #scenario state'
179 objectUnderTest.saveCmHandleState(cmHandleId, compositeState)
180 then: 'update node leaves is invoked with the correct params'
181 1 * mockCpsDataService.updateDataNodeAndDescendants(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle\']', expectedJsonData, _ as OffsetDateTime, ContentType.JSON)
182 where: 'the following states are used'
183 scenario | cmHandleState || expectedJsonData
184 'READY' | CmHandleState.READY || '{"state":{"cm-handle-state":"READY","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
185 'LOCKED' | CmHandleState.LOCKED || '{"state":{"cm-handle-state":"LOCKED","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
186 'DELETING' | CmHandleState.DELETING || '{"state":{"cm-handle-state":"DELETING","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
189 def 'Update Cm Handles with #scenario States'() {
190 given: 'a map of cm handles composite states'
191 def compositeState1 = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
192 def compositeState2 = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
193 when: 'update cm handle state is invoked with the #scenario state'
194 def cmHandleStateMap = ['Some-Cm-Handle1' : compositeState1, 'Some-Cm-Handle2' : compositeState2]
195 objectUnderTest.saveCmHandleStateBatch(cmHandleStateMap)
196 then: 'update node leaves is invoked with the correct params'
197 1 * mockCpsDataService.updateDataNodesAndDescendants(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, cmHandlesJsonDataMap, _ as OffsetDateTime, ContentType.JSON)
198 where: 'the following states are used'
199 scenario | cmHandleState || cmHandlesJsonDataMap
200 'READY' | CmHandleState.READY || ['/dmi-registry/cm-handles[@id=\'Some-Cm-Handle1\']':'{"state":{"cm-handle-state":"READY","last-update-time":"2022-12-31T20:30:40.000+0000"}}', '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle2\']':'{"state":{"cm-handle-state":"READY","last-update-time":"2022-12-31T20:30:40.000+0000"}}']
201 'LOCKED' | CmHandleState.LOCKED || ['/dmi-registry/cm-handles[@id=\'Some-Cm-Handle1\']':'{"state":{"cm-handle-state":"LOCKED","last-update-time":"2022-12-31T20:30:40.000+0000"}}', '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle2\']':'{"state":{"cm-handle-state":"LOCKED","last-update-time":"2022-12-31T20:30:40.000+0000"}}']
202 'DELETING' | CmHandleState.DELETING || ['/dmi-registry/cm-handles[@id=\'Some-Cm-Handle1\']':'{"state":{"cm-handle-state":"DELETING","last-update-time":"2022-12-31T20:30:40.000+0000"}}', '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle2\']':'{"state":{"cm-handle-state":"DELETING","last-update-time":"2022-12-31T20:30:40.000+0000"}}']
205 def 'Getting module definitions by module'() {
206 given: 'cps module service returns module definition for module name'
207 def moduleDefinitions = [new ModuleDefinition('moduleName','revision','content')]
208 mockCpsModuleService.getModuleDefinitionsByAnchorAndModule(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id', 'some-module', '2024-01-25') >> moduleDefinitions
209 when: 'get module definitions is invoked with module name'
210 def result = objectUnderTest.getModuleDefinitionsByCmHandleAndModule('some-cmHandle-Id', 'some-module', '2024-01-25')
211 then: 'returned result are the same module definitions as returned from module service'
212 assert result == moduleDefinitions
213 and: 'cm handle id and module name validated'
214 1 * mockCpsValidator.validateNameCharacters('some-cmHandle-Id', 'some-module')
217 def 'Getting module definitions with cm handle id'() {
218 given: 'cps module service returns module definitions for cm handle id'
219 def moduleDefinitions = [new ModuleDefinition('moduleName','revision','content')]
220 mockCpsModuleService.getModuleDefinitionsByAnchorName(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id') >> moduleDefinitions
221 when: 'get module definitions is invoked with cm handle id'
222 def result = objectUnderTest.getModuleDefinitionsByCmHandleId('some-cmHandle-Id')
223 then: 'the returned result are the same module definitions as returned from the module service'
224 assert result == moduleDefinitions
227 def 'Get module references'() {
228 given: 'cps module service returns a collection of module references'
229 def moduleReferences = [new ModuleReference('moduleName','revision','namespace')]
230 mockCpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id') >> moduleReferences
231 when: 'get yang resources module references by cmHandle is invoked'
232 def result = objectUnderTest.getYangResourcesModuleReferences('some-cmHandle-Id')
233 then: 'the returned result is a collection of module definitions'
234 assert result == moduleReferences
235 and: 'the CM Handle ID is validated'
236 1 * mockCpsValidator.validateNameCharacters('some-cmHandle-Id')
239 def 'Save Cmhandle'() {
240 given: 'cmHandle represented as Yang Model'
241 def yangModelCmHandle = new YangModelCmHandle(id: 'cmhandle', dmiProperties: [], publicProperties: [])
242 when: 'the method to save cmhandle is called'
243 objectUnderTest.saveCmHandle(yangModelCmHandle)
244 then: 'the data service method to save list elements is called once'
245 1 * mockCpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
246 _,null, ContentType.JSON) >> {
248 assert args[3].startsWith('{"cm-handles":[{"id":"cmhandle","additional-properties":[],"public-properties":[]}]}')
253 def 'Save Multiple Cmhandles'() {
254 given: 'cm handles represented as Yang Model'
255 def yangModelCmHandle1 = new YangModelCmHandle(id: 'cmhandle1')
256 def yangModelCmHandle2 = new YangModelCmHandle(id: 'cmhandle2')
257 when: 'the cm handles are saved'
258 objectUnderTest.saveCmHandleBatch([yangModelCmHandle1, yangModelCmHandle2])
259 then: 'CPS Data Service persists both cm handles as a batch'
260 1 * mockCpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
261 NCMP_DMI_REGISTRY_PARENT, _,null, ContentType.JSON) >> {
263 def jsonData = (args[3] as String)
264 jsonData.contains('cmhandle1')
265 jsonData.contains('cmhandle2')
270 def 'Delete list or list elements'() {
271 when: 'the method to delete list or list elements is called'
272 objectUnderTest.deleteListOrListElement('sample xPath')
273 then: 'the data service method to save list elements is called once'
274 1 * mockCpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xPath',null)
277 def 'Get data node via xPath'() {
278 when: 'the method to get data nodes is called'
279 objectUnderTest.getDataNode('sample xPath')
280 then: 'the data persistence service method to get data node is invoked once'
281 1 * mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xPath', INCLUDE_ALL_DESCENDANTS)
284 def 'Get cmHandle data node'() {
285 given: 'expected xPath to get cmHandle data node'
286 def expectedXPath = '/dmi-registry/cm-handles[@id=\'sample cmHandleId\']'
287 when: 'the method to get data nodes is called'
288 objectUnderTest.getCmHandleDataNodeByCmHandleId('sample cmHandleId', INCLUDE_ALL_DESCENDANTS)
289 then: 'the data persistence service method to get cmHandle data node is invoked once with expected xPath'
290 1 * mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, expectedXPath, INCLUDE_ALL_DESCENDANTS)
293 def 'Get CM handle ids for CM Handles that has given module names'() {
294 when: 'the method to get cm handles is called'
295 objectUnderTest.getCmHandleReferencesWithGivenModules(['sample-module-name'], false)
296 then: 'the admin persistence service method to query anchors is invoked once with the same parameter'
297 1 * mockCpsAnchorService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, ['sample-module-name'])
300 def 'Get Alternate Ids for CM Handles that has given module names'() {
301 given: 'cps anchor service returns a CM-handle ID for the given module name'
302 mockCpsAnchorService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, ['sample-module-name']) >> ['ch-1']
303 and: 'cps data service returns some data nodes for the given CM-handle ID'
304 def dataNodes = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='ch-1']", leaves: ['id': 'ch-1', 'alternate-id': 'alt-1'])]
305 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, ["/dmi-registry/cm-handles[@id='ch-1']"], OMIT_DESCENDANTS) >> dataNodes
306 when: 'the method to get cm-handle references by modules is called (outputting alternate IDs)'
307 def result = objectUnderTest.getCmHandleReferencesWithGivenModules(['sample-module-name'], true)
308 then: 'the result contains the correct alternate Id'
309 assert result == ['alt-1'] as Set
312 def 'Replace list content'() {
313 when: 'replace list content method is called with xpath and data nodes collection'
314 objectUnderTest.replaceListContent('sample xpath', [new DataNode()])
315 then: 'the cps data service method to replace list content is invoked once with same parameters'
316 1 * mockCpsDataService.replaceListContent(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xpath', [new DataNode()], NO_TIMESTAMP);
319 def 'Delete data node via xPath'() {
320 when: 'Delete data node method is called with xpath as parameter'
321 objectUnderTest.deleteDataNode('sample dataNode xpath')
322 then: 'the cps data service method to delete data node is invoked once with the same xPath'
323 1 * mockCpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, 'sample dataNode xpath', NO_TIMESTAMP);
326 def 'Delete multiple data nodes via xPath'() {
327 when: 'Delete data nodes method is called with multiple xpaths as parameters'
328 objectUnderTest.deleteDataNodes(['xpath1', 'xpath2'])
329 then: 'the cps data service method to delete data nodes is invoked once with the same xPaths'
330 1 * mockCpsDataService.deleteDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, ['xpath1', 'xpath2'], NO_TIMESTAMP);
333 def 'CM handle exists'() {
334 given: 'data service returns a datanode with correct cm handle id'
335 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, OMIT_DESCENDANTS) >> [dataNode]
336 expect: 'cm handle exists for given cm handle id'
337 assert true == objectUnderTest.isExistingCmHandleId(cmHandleId)
340 def 'CM handle does not exist, empty dataNode collection returned'() {
341 given: 'data service returns an empty datanode'
342 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, OMIT_DESCENDANTS) >> []
343 expect: 'false is returned for non-existent cm handle'
344 assert false == objectUnderTest.isExistingCmHandleId(cmHandleId)
347 def 'CM handle does not exist, exception thrown'() {
348 given: 'data service throws an exception'
349 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, "/dmi-registry/cm-handles[@id='non-existent-cm-handle']", OMIT_DESCENDANTS) >> {throw new DataNodeNotFoundException('','')}
350 expect: 'false is returned for non-existent cm handle'
351 assert false == objectUnderTest.isExistingCmHandleId('non-existent-cm-handle')