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='name1']", leaves: leaves)
83 def childDataNodesForCmHandleWithAllProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some cm handle']/additional-properties[@name='name1']", leaves: ["name":"name1", "value":"value1"]),
84 new DataNode(xpath: "/dmi-registry/cm-handles[@id='some cm handle']/public-properties[@name='name2']", leaves: ["name":"name2","value":"value2"])]
87 def childDataNodesForCmHandleWithDMIProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some-cm-handle']/additional-properties[@name='name1']", leaves: ["name":"name1", "value":"value1"])]
90 def childDataNodesForCmHandleWithPublicProperties = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='some-cm-handle']/public-properties[@name='name2']", leaves: ["name":"name2","value":"value2"])]
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 DMI properties'
107 result.dmiProperties == expectedDmiProperties
108 result.publicProperties == expectedPublicProperties
109 and: 'the state details are returned'
110 result.compositeState.cmHandleState == expectedCompositeState
111 and: 'the CM Handle ID is validated'
112 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
113 where: 'the following parameters are used'
114 scenario | childDataNodes || expectedDmiProperties || expectedPublicProperties || expectedCompositeState
115 'no properties' | [] || [] || [] || null
116 'DMI and public properties' | childDataNodesForCmHandleWithAllProperties || [new YangModelCmHandle.Property("name1", "value1")] || [new YangModelCmHandle.Property("name2", "value2")] || null
117 'just DMI properties' | childDataNodesForCmHandleWithDMIProperties || [new YangModelCmHandle.Property("name1", "value1")] || [] || null
118 'just public properties' | childDataNodesForCmHandleWithPublicProperties || [] || [new YangModelCmHandle.Property("name2", "value2")] || null
119 'with state details' | childDataNodesForCmHandleWithState || [] || [] || CmHandleState.ADVISED
122 def 'Handling missing service names as null.'() {
123 given: 'the cps data service returns a data node from the DMI registry with empty child and leaf attributes'
124 def dataNode = new DataNode(childDataNodes:[], leaves: ['id':cmHandleId])
125 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
126 when: 'retrieving the yang modelled cm handle'
127 def result = objectUnderTest.getYangModelCmHandle(cmHandleId)
128 then: 'the service names are returned as null'
129 result.dmiServiceName == null
130 result.dmiDataServiceName == null
131 result.dmiModelServiceName == null
132 and: 'the CM Handle ID is validated'
133 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
136 def 'Retrieve multiple YangModelCmHandles using cm handle ids'() {
137 given: 'the cps data service returns 2 data nodes from the DMI registry'
138 def dataNodes = [new DataNode(xpath: xpath, leaves: ['id': cmHandleId]), new DataNode(xpath: xpath2, leaves: ['id': cmHandleId2])]
139 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, [xpath, xpath2] , INCLUDE_ALL_DESCENDANTS) >> dataNodes
140 when: 'retrieving the yang modelled cm handles'
141 def results = objectUnderTest.getYangModelCmHandles([cmHandleId, cmHandleId2])
142 then: 'verify both have returned and cm handle Ids are correct'
143 assert results.size() == 2
144 assert results.id.containsAll([cmHandleId, cmHandleId2])
147 def 'YangModelCmHandles are not returned for invalid cm handle ids'() {
148 given: 'invalid cm handle id throws a data validation exception'
149 mockCpsValidator.validateNameCharacters('Invalid Cm Handle Id') >> {throw new DataValidationException('','')}
150 and: 'empty collection is returned as no valid cm handle ids are given'
151 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, [] , INCLUDE_ALL_DESCENDANTS) >> []
152 when: 'retrieving the yang modelled cm handles'
153 def results = objectUnderTest.getYangModelCmHandles(['Invalid Cm Handle Id'])
154 then: 'no YangModelCmHandle is returned'
155 assert results.size() == 0
158 def 'Get a Cm Handle Composite State'() {
159 given: 'a valid cm handle id'
160 def cmHandleId = 'Some-Cm-Handle'
161 def dataNode = new DataNode(leaves: ['cm-handle-state': 'ADVISED'])
162 and: 'cps data service returns a valid data node'
163 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
164 '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle\']/state', INCLUDE_ALL_DESCENDANTS) >> [dataNode]
165 when: 'get cm handle state is invoked'
166 def result = objectUnderTest.getCmHandleState(cmHandleId)
167 then: 'result has returned the correct cm handle state'
168 result.cmHandleState == CmHandleState.ADVISED
169 and: 'the CM Handle ID is validated'
170 1 * mockCpsValidator.validateNameCharacters(cmHandleId)
173 def 'Update Cm Handle with #scenario State'() {
174 given: 'a cm handle and a composite state'
175 def cmHandleId = 'Some-Cm-Handle'
176 def compositeState = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
177 when: 'update cm handle state is invoked with the #scenario state'
178 objectUnderTest.saveCmHandleState(cmHandleId, compositeState)
179 then: 'update node leaves is invoked with the correct params'
180 1 * mockCpsDataService.updateDataNodeAndDescendants(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, '/dmi-registry/cm-handles[@id=\'Some-Cm-Handle\']', expectedJsonData, _ as OffsetDateTime, ContentType.JSON)
181 where: 'the following states are used'
182 scenario | cmHandleState || expectedJsonData
183 'READY' | CmHandleState.READY || '{"state":{"cm-handle-state":"READY","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
184 'LOCKED' | CmHandleState.LOCKED || '{"state":{"cm-handle-state":"LOCKED","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
185 'DELETING' | CmHandleState.DELETING || '{"state":{"cm-handle-state":"DELETING","last-update-time":"2022-12-31T20:30:40.000+0000"}}'
188 def 'Update Cm Handles with #scenario States'() {
189 given: 'a map of cm handles composite states'
190 def compositeState1 = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
191 def compositeState2 = new CompositeState(cmHandleState: cmHandleState, lastUpdateTime: formattedDateAndTime)
192 when: 'update cm handle state is invoked with the #scenario state'
193 def cmHandleStateMap = ['Some-Cm-Handle1' : compositeState1, 'Some-Cm-Handle2' : compositeState2]
194 objectUnderTest.saveCmHandleStateBatch(cmHandleStateMap)
195 then: 'update node leaves is invoked with the correct params'
196 1 * mockCpsDataService.updateDataNodesAndDescendants(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, cmHandlesJsonDataMap, _ as OffsetDateTime, ContentType.JSON)
197 where: 'the following states are used'
198 scenario | cmHandleState || cmHandlesJsonDataMap
199 '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"}}']
200 '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"}}']
201 '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"}}']
204 def 'Getting module definitions by module'() {
205 given: 'cps module service returns module definition for module name'
206 def moduleDefinitions = [new ModuleDefinition('moduleName','revision','content')]
207 mockCpsModuleService.getModuleDefinitionsByAnchorAndModule(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id', 'some-module', '2024-01-25') >> moduleDefinitions
208 when: 'get module definitions is invoked with module name'
209 def result = objectUnderTest.getModuleDefinitionsByCmHandleAndModule('some-cmHandle-Id', 'some-module', '2024-01-25')
210 then: 'returned result are the same module definitions as returned from module service'
211 assert result == moduleDefinitions
212 and: 'cm handle id and module name validated'
213 1 * mockCpsValidator.validateNameCharacters('some-cmHandle-Id', 'some-module')
216 def 'Getting module definitions with cm handle id'() {
217 given: 'cps module service returns module definitions for cm handle id'
218 def moduleDefinitions = [new ModuleDefinition('moduleName','revision','content')]
219 mockCpsModuleService.getModuleDefinitionsByAnchorName(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id') >> moduleDefinitions
220 when: 'get module definitions is invoked with cm handle id'
221 def result = objectUnderTest.getModuleDefinitionsByCmHandleId('some-cmHandle-Id')
222 then: 'the returned result are the same module definitions as returned from the module service'
223 assert result == moduleDefinitions
226 def 'Get module references'() {
227 given: 'cps module service returns a collection of module references'
228 def moduleReferences = [new ModuleReference('moduleName','revision','namespace')]
229 mockCpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,'some-cmHandle-Id') >> moduleReferences
230 when: 'get yang resources module references by cmHandle is invoked'
231 def result = objectUnderTest.getYangResourcesModuleReferences('some-cmHandle-Id')
232 then: 'the returned result is a collection of module definitions'
233 assert result == moduleReferences
234 and: 'the CM Handle ID is validated'
235 1 * mockCpsValidator.validateNameCharacters('some-cmHandle-Id')
238 def 'Save Cmhandle'() {
239 given: 'cmHandle represented as Yang Model'
240 def yangModelCmHandle = new YangModelCmHandle(id: 'cmhandle', dmiProperties: [], publicProperties: [])
241 when: 'the method to save cmhandle is called'
242 objectUnderTest.saveCmHandle(yangModelCmHandle)
243 then: 'the data service method to save list elements is called once'
244 1 * mockCpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
245 _,null, ContentType.JSON) >> {
247 assert args[3].startsWith('{"cm-handles":[{"id":"cmhandle","additional-properties":[],"public-properties":[]}]}')
252 def 'Save Multiple Cmhandles'() {
253 given: 'cm handles represented as Yang Model'
254 def yangModelCmHandle1 = new YangModelCmHandle(id: 'cmhandle1')
255 def yangModelCmHandle2 = new YangModelCmHandle(id: 'cmhandle2')
256 when: 'the cm handles are saved'
257 objectUnderTest.saveCmHandleBatch([yangModelCmHandle1, yangModelCmHandle2])
258 then: 'CPS Data Service persists both cm handles as a batch'
259 1 * mockCpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
260 NCMP_DMI_REGISTRY_PARENT, _,null, ContentType.JSON) >> {
262 def jsonData = (args[3] as String)
263 jsonData.contains('cmhandle1')
264 jsonData.contains('cmhandle2')
269 def 'Delete list or list elements'() {
270 when: 'the method to delete list or list elements is called'
271 objectUnderTest.deleteListOrListElement('sample xPath')
272 then: 'the data service method to save list elements is called once'
273 1 * mockCpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xPath',null)
276 def 'Get data node via xPath'() {
277 when: 'the method to get data nodes is called'
278 objectUnderTest.getDataNode('sample xPath')
279 then: 'the data persistence service method to get data node is invoked once'
280 1 * mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xPath', INCLUDE_ALL_DESCENDANTS)
283 def 'Get cmHandle data node'() {
284 given: 'expected xPath to get cmHandle data node'
285 def expectedXPath = '/dmi-registry/cm-handles[@id=\'sample cmHandleId\']'
286 when: 'the method to get data nodes is called'
287 objectUnderTest.getCmHandleDataNodeByCmHandleId('sample cmHandleId', INCLUDE_ALL_DESCENDANTS)
288 then: 'the data persistence service method to get cmHandle data node is invoked once with expected xPath'
289 1 * mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, expectedXPath, INCLUDE_ALL_DESCENDANTS)
292 def 'Get CM handle ids for CM Handles that has given module names'() {
293 when: 'the method to get cm handles is called'
294 objectUnderTest.getCmHandleReferencesWithGivenModules(['sample-module-name'], false)
295 then: 'the admin persistence service method to query anchors is invoked once with the same parameter'
296 1 * mockCpsAnchorService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, ['sample-module-name'])
299 def 'Get Alternate Ids for CM Handles that has given module names'() {
300 given: 'cps anchor service returns a CM-handle ID for the given module name'
301 mockCpsAnchorService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, ['sample-module-name']) >> ['ch-1']
302 and: 'cps data service returns some data nodes for the given CM-handle ID'
303 def dataNodes = [new DataNode(xpath: "/dmi-registry/cm-handles[@id='ch-1']", leaves: ['id': 'ch-1', 'alternate-id': 'alt-1'])]
304 mockCpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, ["/dmi-registry/cm-handles[@id='ch-1']"], OMIT_DESCENDANTS) >> dataNodes
305 when: 'the method to get cm-handle references by modules is called (outputting alternate IDs)'
306 def result = objectUnderTest.getCmHandleReferencesWithGivenModules(['sample-module-name'], true)
307 then: 'the result contains the correct alternate Id'
308 assert result == ['alt-1'] as Set
311 def 'Replace list content'() {
312 when: 'replace list content method is called with xpath and data nodes collection'
313 objectUnderTest.replaceListContent('sample xpath', [new DataNode()])
314 then: 'the cps data service method to replace list content is invoked once with same parameters'
315 1 * mockCpsDataService.replaceListContent(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,'sample xpath', [new DataNode()], NO_TIMESTAMP);
318 def 'Delete data node via xPath'() {
319 when: 'Delete data node method is called with xpath as parameter'
320 objectUnderTest.deleteDataNode('sample dataNode xpath')
321 then: 'the cps data service method to delete data node is invoked once with the same xPath'
322 1 * mockCpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, 'sample dataNode xpath', NO_TIMESTAMP);
325 def 'Delete multiple data nodes via xPath'() {
326 when: 'Delete data nodes method is called with multiple xpaths as parameters'
327 objectUnderTest.deleteDataNodes(['xpath1', 'xpath2'])
328 then: 'the cps data service method to delete data nodes is invoked once with the same xPaths'
329 1 * mockCpsDataService.deleteDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, ['xpath1', 'xpath2'], NO_TIMESTAMP);
332 def 'CM handle exists'() {
333 given: 'data service returns a datanode with correct cm handle id'
334 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, OMIT_DESCENDANTS) >> [dataNode]
335 expect: 'cm handle exists for given cm handle id'
336 assert true == objectUnderTest.isExistingCmHandleId(cmHandleId)
339 def 'CM handle does not exist, empty dataNode collection returned'() {
340 given: 'data service returns an empty datanode'
341 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpath, OMIT_DESCENDANTS) >> []
342 expect: 'false is returned for non-existent cm handle'
343 assert false == objectUnderTest.isExistingCmHandleId(cmHandleId)
346 def 'CM handle does not exist, exception thrown'() {
347 given: 'data service throws an exception'
348 mockCpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, "/dmi-registry/cm-handles[@id='non-existent-cm-handle']", OMIT_DESCENDANTS) >> {throw new DataNodeNotFoundException('','')}
349 expect: 'false is returned for non-existent cm handle'
350 assert false == objectUnderTest.isExistingCmHandleId('non-existent-cm-handle')