2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2023 Nordix Foundation
4 * Modifications Copyright (C) 2021 Pantheon.tech
5 * Modifications Copyright (C) 2021-2022 Bell Canada.
6 * Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl
26 import com.fasterxml.jackson.databind.ObjectMapper
27 import com.google.common.collect.ImmutableSet
28 import org.onap.cps.spi.CpsDataPersistenceService
29 import org.onap.cps.spi.entities.FragmentEntity
30 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch
31 import org.onap.cps.spi.exceptions.AnchorNotFoundException
32 import org.onap.cps.spi.exceptions.CpsAdminException
33 import org.onap.cps.spi.exceptions.CpsPathException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
36 import org.onap.cps.spi.model.DataNode
37 import org.onap.cps.spi.model.DataNodeBuilder
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.springframework.beans.factory.annotation.Autowired
40 import org.springframework.test.context.jdbc.Sql
42 import javax.validation.ConstraintViolationException
44 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
45 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
47 class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
50 CpsDataPersistenceService objectUnderTest
52 static JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
53 static DataNodeBuilder dataNodeBuilder = new DataNodeBuilder()
55 static final String SET_DATA = '/data/fragment.sql'
56 static long ID_DATA_NODE_WITH_DESCENDANTS = 4001
57 static String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
58 static long DATA_NODE_202_FRAGMENT_ID = 4202L
59 static long CHILD_OF_DATA_NODE_202_FRAGMENT_ID = 4203L
60 static long LIST_DATA_NODE_PARENT201_FRAGMENT_ID = 4206L
61 static long LIST_DATA_NODE_PARENT203_FRAGMENT_ID = 4214L
62 static long LIST_DATA_NODE_PARENT202_FRAGMENT_ID = 4211L
63 static long PARENT_3_FRAGMENT_ID = 4003L
65 static Collection<DataNode> newDataNodes = [new DataNodeBuilder().build()]
66 static Collection<DataNode> existingDataNodes = [createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)]
67 static Collection<DataNode> existingChildDataNodes = [createDataNodeTree('/parent-1/child-1')]
69 def static deleteTestParentXPath = '/parent-200'
70 def static deleteTestChildXpath = "${deleteTestParentXPath}/child-with-slash[@key='a/b']"
71 def static deleteTestGrandChildXPath = "${deleteTestChildXpath}/grandChild"
73 @Sql([CLEAR_DATA, SET_DATA])
74 def 'Get all datanodes with descendants .'() {
75 when: 'data nodes are retrieved by their xpath'
76 def dataNodes = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_NAME1, ['/parent-1'], INCLUDE_ALL_DESCENDANTS)
77 then: 'same data nodes are returned by getDataNodesForMultipleXpaths method'
78 assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME1, '/parent-1', INCLUDE_ALL_DESCENDANTS) == dataNodes
79 and: 'the dataNodes have no prefix (to be addressed by CPS-1301)'
80 assert dataNodes[0].moduleNamePrefix == null
83 @Sql([CLEAR_DATA, SET_DATA])
84 def 'Storing and Retrieving a new DataNodes with descendants.'() {
85 when: 'a fragment with descendants is stored'
86 def parentXpath = '/parent-new'
87 def childXpath = '/parent-new/child-new'
88 def grandChildXpath = '/parent-new/child-new/grandchild-new'
89 def dataNodes = [createDataNodeTree(parentXpath, childXpath, grandChildXpath)]
90 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, dataNodes)
91 then: 'it can be retrieved by its xpath'
92 def dataNode = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, INCLUDE_ALL_DESCENDANTS)
93 assert dataNode[0].xpath == parentXpath
94 and: 'it has the correct child'
95 assert dataNode[0].childDataNodes.size() == 1
96 def childDataNode = dataNode[0].childDataNodes[0]
97 assert childDataNode.xpath == childXpath
98 and: 'and its grandchild'
99 assert childDataNode.childDataNodes.size() == 1
100 def grandChildDataNode = childDataNode.childDataNodes[0]
101 assert grandChildDataNode.xpath == grandChildXpath
104 @Sql([CLEAR_DATA, SET_DATA])
105 def 'Store data node for multiple anchors using the same schema.'() {
106 def xpath = '/parent-new'
107 given: 'a fragment is stored for an anchor'
108 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, [createDataNodeTree(xpath)])
109 when: 'another fragment is stored for an other anchor, using the same schema set'
110 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME3, [createDataNodeTree(xpath)])
111 then: 'both fragments can be retrieved by their xpath'
112 def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
113 fragment1.anchor.name == ANCHOR_NAME1
114 fragment1.xpath == xpath
115 def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
116 fragment2.anchor.name == ANCHOR_NAME3
117 fragment2.xpath == xpath
120 @Sql([CLEAR_DATA, SET_DATA])
121 def 'Store datanodes error scenario: #scenario.'() {
122 when: 'attempt to store a data node with #scenario'
123 objectUnderTest.storeDataNodes(dataspaceName, anchorName, dataNodes)
124 then: 'a #expectedException is thrown'
125 thrown(expectedException)
126 where: 'the following data is used'
127 scenario | dataspaceName | anchorName | dataNodes || expectedException
128 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNodes || DataspaceNotFoundException
129 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNodes || AnchorNotFoundException
130 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNodes || ConstraintViolationException
131 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNodes || AlreadyDefinedExceptionBatch
134 @Sql([CLEAR_DATA, SET_DATA])
135 def 'Add children to a Fragment that already has a child.'() {
136 given: 'collection of new child data nodes'
137 def newChild1 = createDataNodeTree('/parent-1/child-2')
138 def newChild2 = createDataNodeTree('/parent-1/child-3')
139 def newChildrenCollection = [newChild1, newChild2]
140 when: 'the child is added to an existing parent with 1 child'
141 objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChildrenCollection)
142 then: 'the parent is now has to 3 children'
143 def expectedExistingChildPath = '/parent-1/child-1'
144 def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
145 parentFragment.childFragments.size() == 3
146 and: 'it still has the old child'
147 parentFragment.childFragments.find({ it.xpath == expectedExistingChildPath })
148 and: 'it has the new children'
149 parentFragment.childFragments.find({ it.xpath == newChildrenCollection[0].xpath })
150 parentFragment.childFragments.find({ it.xpath == newChildrenCollection[1].xpath })
153 @Sql([CLEAR_DATA, SET_DATA])
154 def 'Add child error scenario: #scenario.'() {
155 when: 'attempt to add a child data node with #scenario'
156 objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNodes)
157 then: 'a #expectedException is thrown'
158 thrown(expectedException)
159 where: 'the following data is used'
160 scenario | parentXpath | dataNodes || expectedException
161 'parent does not exist' | '/unknown' | newDataNodes || DataNodeNotFoundException
162 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNodes || AlreadyDefinedExceptionBatch
165 @Sql([CLEAR_DATA, SET_DATA])
166 def 'Add collection of multiple new list elements including an element with a child datanode.'() {
167 given: 'two new child list elements for an existing parent'
168 def listElementXpaths = ['/parent-201/child-204[@key="NEW1"]', '/parent-201/child-204[@key="NEW2"]']
169 def listElements = toDataNodes(listElementXpaths)
170 and: 'a (grand)child data node for one of the new list elements'
171 def grandChild = buildDataNode('/parent-201/child-204[@key="NEW1"]/grand-child-204[@key2="NEW1-CHILD"]', [leave:'value'], [])
172 listElements[0].childDataNodes = [grandChild]
173 when: 'the new data node (list elements) are added to an existing parent node'
174 objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', [listElements])
175 then: 'new entries are successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
176 def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT201_FRAGMENT_ID)
177 def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
178 assert allChildXpaths.size() == 5
179 assert allChildXpaths.containsAll(listElementXpaths)
180 and: 'the (grand)child node of the new list entry is also present'
181 def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
182 def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_NAME3)
183 def grandChildFragmentEntity = fragmentRepository.findByAnchorAndXpath(anchorEntity, grandChild.xpath)
184 assert grandChildFragmentEntity.isPresent()
187 @Sql([CLEAR_DATA, SET_DATA])
188 def 'Add multiple list with a mix of existing and new elements'() {
189 given: 'two new child list elements for an existing parent'
190 def existingDataNode = dataNodeBuilder.withXpath('/parent-207/child-001').withLeaves(['id': '001']).build()
191 def newDataNode1 = dataNodeBuilder.withXpath('/parent-207/child-new1').withLeaves(['id': 'new1']).build()
192 def newDataNode2 = dataNodeBuilder.withXpath('/parent-200/child-new2').withLeaves(['id': 'new2']).build()
193 def dataNodeList1 = [existingDataNode, newDataNode1]
194 def dataNodeList2 = [newDataNode2]
195 when: 'duplicate data node is requested to be added'
196 objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT, '/', [dataNodeList1, dataNodeList2])
197 then: 'already defined batch exception is thrown'
198 def thrown = thrown(AlreadyDefinedExceptionBatch)
199 and: 'it only contains the xpath(s) of the duplicated elements'
200 assert thrown.alreadyDefinedXpaths.size() == 1
201 assert thrown.alreadyDefinedXpaths.contains('/parent-207/child-001')
202 and: 'it does NOT contains the xpaths of the new element that were not combined with existing elements'
203 assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
204 assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
205 and: 'the new entity is inserted correctly'
206 def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
207 def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT)
208 fragmentRepository.findByAnchorAndXpath(anchorEntity, '/parent-200/child-new2').isPresent()
211 @Sql([CLEAR_DATA, SET_DATA])
212 def 'Add list element error scenario: #scenario.'() {
213 given: 'list element as a collection of data nodes'
214 def listElements = toDataNodes(listElementXpaths)
215 when: 'attempt to add list elements to parent node'
216 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listElements)
217 then: 'a #expectedException is thrown'
218 thrown(expectedException)
219 where: 'following parameters were used'
220 scenario | parentNodeXpath | listElementXpaths || expectedException
221 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
222 'data fragment already exists' | '/parent-201' | ["/parent-201/child-204[@key='A']"] || AlreadyDefinedExceptionBatch
225 @Sql([CLEAR_DATA, SET_DATA])
226 def 'Get all data nodes by single xpath without descendants : #scenario'() {
227 when: 'data nodes are requested'
228 def result = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
229 [inputXPath], OMIT_DESCENDANTS)
230 then: 'data nodes under root are returned'
231 assert result.childDataNodes.size() == 2
232 and: 'no descendants of parent nodes are returned'
233 result.each {assert it.childDataNodes.size() == 0}
234 and: 'same data nodes are returned when V2 of get Data Nodes API is executed'
235 assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
236 inputXPath, OMIT_DESCENDANTS) == result
237 where: 'the following xpath is used'
238 scenario | inputXPath
243 @Sql([CLEAR_DATA, SET_DATA])
244 def 'Cps Path query with syntax error throws a CPS Path Exception.'() {
245 when: 'trying to execute a query with a syntax (parsing) error'
246 objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, 'invalid-cps-path/child' , OMIT_DESCENDANTS)
247 then: 'exception is thrown'
248 def exceptionThrown = thrown(CpsPathException)
249 assert exceptionThrown.getDetails() == "failed to parse at line 1 due to extraneous input 'invalid-cps-path' expecting '/'"
252 @Sql([CLEAR_DATA, SET_DATA])
253 def 'Get all data nodes by single xpath with all descendants : #scenario'() {
254 when: 'data nodes are requested with all descendants'
255 def result = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
256 [inputXPath], INCLUDE_ALL_DESCENDANTS)
257 def mappedResult = multipleTreesToFlatMapByXpath(new HashMap<>(), result)
258 then: 'data nodes are returned with all the descendants populated'
259 assert mappedResult.size() == 8
260 assert result.childDataNodes.size() == 2
261 assert mappedResult.get('/parent-208/child-001').childDataNodes.size() == 0
262 assert mappedResult.get('/parent-208/child-002').childDataNodes.size() == 1
263 assert mappedResult.get('/parent-209/child-001').childDataNodes.size() == 0
264 assert mappedResult.get('/parent-209/child-002').childDataNodes.size() == 1
265 and: 'same data nodes are returned when V2 of Get Data Nodes API is executed'
266 assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
267 inputXPath, INCLUDE_ALL_DESCENDANTS) == result
268 where: 'the following data is used'
269 scenario | inputXPath
274 @Sql([CLEAR_DATA, SET_DATA])
275 def 'Get data nodes error scenario : #scenario.'() {
276 when: 'attempt to get data nodes with #scenario'
277 objectUnderTest.getDataNodes(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
278 then: 'an #expectedException is thrown'
279 thrown(expectedException)
280 where: 'the following data is used'
281 scenario | dataspaceName | anchorName | xpath || expectedException
282 'non existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NO-XPATH' || DataNodeNotFoundException
283 'invalid Xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH' || CpsPathException
286 @Sql([CLEAR_DATA, SET_DATA])
287 def 'Get data nodes for multiple xpaths.'() {
288 when: 'fetch #scenario.'
289 def results = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_NAME3, inputXpaths, OMIT_DESCENDANTS)
290 then: 'the expected number of data nodes are returned'
291 assert results.size() == expectedResultSize
292 where: 'following parameters were used'
293 scenario | inputXpaths || expectedResultSize
295 '1 node' | ["/parent-200"] || 1
296 '2 unique nodes' | ["/parent-200", "/parent-201"] || 2
297 '3 unique nodes' | ["/parent-200", "/parent-201", "/parent-202"] || 3
298 '1 unique node with duplicate xpath' | ["/parent-200", "/parent-200"] || 1
299 '2 unique nodes with duplicate xpath' | ["/parent-200", "/parent-202", "/parent-200"] || 2
300 'list element with key (single quote)' | ["/parent-201/child-204[@key='A']"] || 1
301 'list element with key (double quote)' | ['/parent-201/child-204[@key="A"]'] || 1
302 'whole list (not implemented)' | ["/parent-201/child-204"] || 0
303 'non-existing xpath' | ["/NO-XPATH"] || 0
304 'existing and non-existing xpaths' | ["/parent-200", "/NO-XPATH", "/parent-201"] || 2
305 'invalid xpath' | ["INVALID XPATH"] || 0
306 'valid and invalid xpaths' | ["/parent-200", "INVALID XPATH", "/parent-201"] || 2
307 'root xpath' | ["/"] || 7
308 'empty (root) xpath' | [""] || 7
309 'root and top-level xpaths' | ["/", "/parent-200", "/parent-201"] || 7
310 'root and child xpaths' | ["/", "/parent-200/child-201"] || 8
313 @Sql([CLEAR_DATA, SET_DATA])
314 def 'Get data nodes for collection of xpath error scenario : #scenario.'() {
315 when: 'attempt to get data nodes with #scenario'
316 objectUnderTest.getDataNodesForMultipleXpaths(dataspaceName, anchorName, ['/not-relevant'], OMIT_DESCENDANTS)
317 then: 'a #expectedException is thrown'
318 thrown(expectedException)
319 where: 'the following data is used'
320 scenario | dataspaceName | anchorName || expectedException
321 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' || DataspaceNotFoundException
322 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' || AnchorNotFoundException
325 @Sql([CLEAR_DATA, SET_DATA])
326 def 'Update data node leaves.'() {
327 when: 'update is performed for leaves'
328 objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
329 '/parent-200/child-201', ['leaf-value': 'new'])
330 then: 'leaves are updated for selected data node'
331 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
332 def updatedLeaves = getLeavesMap(updatedFragment)
333 assert updatedLeaves.size() == 1
334 assert updatedLeaves.'leaf-value' == 'new'
335 and: 'existing child entry remains as is'
336 def childFragment = updatedFragment.childFragments.iterator().next()
337 def childLeaves = getLeavesMap(childFragment)
338 assert childFragment.id == CHILD_OF_DATA_NODE_202_FRAGMENT_ID
339 assert childLeaves.'leaf-value' == 'original'
342 @Sql([CLEAR_DATA, SET_DATA])
343 def 'Update data leaves error scenario: #scenario.'() {
344 when: 'attempt to update data node for #scenario'
345 objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
346 then: 'a #expectedException is thrown'
347 thrown(expectedException)
348 where: 'the following data is used'
349 scenario | dataspaceName | anchorName | xpath || expectedException
350 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | '/not relevant' || DataspaceNotFoundException
351 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | '/not relevant' || AnchorNotFoundException
352 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
355 @Sql([CLEAR_DATA, SET_DATA])
356 def 'Update data node and descendants by removing descendants.'() {
357 given: 'data node object with leaves updated, no children'
358 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [])
359 when: 'update data nodes and descendants is performed'
360 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
361 then: 'leaves have been updated for selected data node'
362 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
363 def updatedLeaves = getLeavesMap(updatedFragment)
364 assert updatedLeaves.size() == 1
365 assert updatedLeaves.'leaf-value' == 'new'
366 and: 'updated entry has no children'
367 updatedFragment.childFragments.isEmpty()
368 and: 'previously attached child entry is removed from database'
369 fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
372 @Sql([CLEAR_DATA, SET_DATA])
373 def 'Update data node and descendants with new descendants'() {
374 given: 'data node object with leaves updated, having child with old content'
375 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
376 buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'original'], [])
378 when: 'update is performed including descendants'
379 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
380 then: 'leaves have been updated for selected data node'
381 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
382 def updatedLeaves = getLeavesMap(updatedFragment)
383 assert updatedLeaves.size() == 1
384 assert updatedLeaves.'leaf-value' == 'new'
385 and: 'existing child entry is not updated as content is same'
386 def childFragment = updatedFragment.childFragments.iterator().next()
387 childFragment.xpath == '/parent-200/child-201/grand-child'
388 def childLeaves = getLeavesMap(childFragment)
389 assert childLeaves.'leaf-value' == 'original'
392 @Sql([CLEAR_DATA, SET_DATA])
393 def 'Update data node and descendants with same descendants but changed leaf value.'() {
394 given: 'data node object with leaves updated, having child with old content'
395 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
396 buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'new'], [])
398 when: 'update is performed including descendants'
399 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
400 then: 'leaves have been updated for selected data node'
401 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
402 def updatedLeaves = getLeavesMap(updatedFragment)
403 assert updatedLeaves.size() == 1
404 assert updatedLeaves.'leaf-value' == 'new'
405 and: 'existing child entry is updated with the new content'
406 def childFragment = updatedFragment.childFragments.iterator().next()
407 childFragment.xpath == '/parent-200/child-201/grand-child'
408 def childLeaves = getLeavesMap(childFragment)
409 assert childLeaves.'leaf-value' == 'new'
412 @Sql([CLEAR_DATA, SET_DATA])
413 def 'Update data node and descendants with different descendants xpath'() {
414 given: 'data node object with leaves updated, having child with old content'
415 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
416 buildDataNode('/parent-200/child-201/grand-child-new', ['leaf-value': 'new'], [])
418 when: 'update is performed including descendants'
419 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
420 then: 'leaves have been updated for selected data node'
421 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
422 def updatedLeaves = getLeavesMap(updatedFragment)
423 assert updatedLeaves.size() == 1
424 assert updatedLeaves.'leaf-value' == 'new'
425 and: 'previously attached child entry is removed from database'
426 fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
427 and: 'new child entry is persisted'
428 def childFragment = updatedFragment.childFragments.iterator().next()
429 childFragment.xpath == '/parent-200/child-201/grand-child-new'
430 def childLeaves = getLeavesMap(childFragment)
431 assert childLeaves.'leaf-value' == 'new'
434 @Sql([CLEAR_DATA, SET_DATA])
435 def 'Update data node and descendants error scenario: #scenario.'() {
436 given: 'data node object'
437 def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
438 when: 'attempt to update data node for #scenario'
439 objectUnderTest.updateDataNodeAndDescendants(dataspaceName, anchorName, submittedDataNode)
440 then: 'a #expectedException is thrown'
441 thrown(expectedException)
442 where: 'the following data is used'
443 scenario | dataspaceName | anchorName | xpath || expectedException
444 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | '/not relevant' || DataspaceNotFoundException
445 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | '/not relevant' || AnchorNotFoundException
446 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
447 'invalid xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH' || CpsPathException
450 @Sql([CLEAR_DATA, SET_DATA])
451 def 'Update existing list with #scenario.'() {
452 given: 'a parent having a list of data nodes containing: #originalKeys (ech list element has a child too)'
453 def parentXpath = '/parent-3'
454 if (originalKeys.size() > 0) {
455 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'original value', originalKeys, true)
456 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
458 and: 'each original list element has one child'
459 def originalParentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
460 originalParentFragment.childFragments.each {assert it.childFragments.size() == 1 }
461 when: 'it is updated with #scenario'
462 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new value', replacementKeys, false)
463 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
464 then: 'the result list ONLY contains the expected replacement elements'
465 def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
466 def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
467 def expectedListEntriesAfterUpdateAsXpaths = keysToXpaths(parentXpath, replacementKeys)
468 assert allChildXpaths.size() == replacementKeys.size()
469 assert allChildXpaths.containsAll(expectedListEntriesAfterUpdateAsXpaths)
470 and: 'all the list elements have the new values'
471 assert parentFragment.childFragments.stream().allMatch(childFragment -> childFragment.attributes.contains('new value'))
472 and: 'there are no more grandchildren as none of the replacement list entries had a child'
473 parentFragment.childFragments.each {assert it.childFragments.size() == 0 }
474 where: 'the following replacement lists are applied'
475 scenario | originalKeys | replacementKeys
476 'one existing entry only' | [] | ['NEW']
477 'multiple new entries' | [] | ['NEW1', 'NEW2']
478 'one new entry only (existing entries are deleted)' | ['A', 'B'] | ['NEW1', 'NEW2']
479 'one existing on new entry' | ['A', 'B'] | ['A', 'NEW']
480 'one existing entry only' | ['A', 'B'] | ['A']
483 @Sql([CLEAR_DATA, SET_DATA])
484 def 'Replacing existing list element with attributes and (grand)child.'() {
485 given: 'a parent with list elements A and B with attribute and grandchild tagged as "org"'
486 def parentXpath = '/parent-3'
487 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'org', ['A','B'], true)
488 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
489 when: 'A is replaced with an entry with attribute and grandchild tagged tagged as "new" (B is not in replacement list)'
490 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new', ['A'], true)
491 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
492 then: 'The updated fragment has a child-list with ONLY element "A"'
493 def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
494 parentFragment.childFragments.size() == 1
495 def childListElementA = parentFragment.childFragments[0]
496 childListElementA.xpath == "/parent-3/child-list[@key='A']"
497 and: 'element "A" has an attribute with the "new" (tag) value'
498 childListElementA.attributes == '{"attr1": "new"}'
499 and: 'element "A" has a only one (grand)child'
500 childListElementA.childFragments.size() == 1
501 and: 'the grandchild is the new grandchild (tag)'
502 def grandChild = childListElementA.childFragments[0]
503 grandChild.xpath == "/parent-3/child-list[@key='A']/new-grand-child"
504 and: 'the grandchild has an attribute with the "new" (tag) value'
505 grandChild.attributes == '{"attr1": "new"}'
508 @Sql([CLEAR_DATA, SET_DATA])
509 def 'Replace list element for a parent (parent-1) with existing one (non-list) child'() {
510 when: 'a list element is added under the parent'
511 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(XPATH_DATA_NODE_WITH_DESCENDANTS, 'new', ['A','B'], false)
512 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, replacementListEntriesAsDataNodes)
513 then: 'the parent will have 3 children after the replacement'
514 def parentFragment = fragmentRepository.getById(ID_DATA_NODE_WITH_DESCENDANTS)
515 parentFragment.childFragments.size() == 3
516 def xpaths = parentFragment.childFragments.collect {it.xpath}
517 and: 'one of the children is the original child fragment'
518 xpaths.contains('/parent-1/child-1')
519 and: 'it has the two new list elements'
520 xpaths.containsAll("/parent-1/child-list[@key='A']", "/parent-1/child-list[@key='B']")
523 @Sql([CLEAR_DATA, SET_DATA])
524 def 'Replace list content using unknown parent'() {
525 given: 'list element as a collection of data nodes'
526 def listElementCollection = toDataNodes(['irrelevant'])
527 when: 'attempt to replace list elements under unknown parent node'
528 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/unknown', listElementCollection)
529 then: 'a datanode not found exception is thrown'
530 thrown(DataNodeNotFoundException)
533 @Sql([CLEAR_DATA, SET_DATA])
534 def 'Replace list content with empty collection is not supported'() {
535 when: 'attempt to replace list elements with empty collection'
536 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/parent-203', [])
537 then: 'a CPS admin exception is thrown'
538 def thrown = thrown(CpsAdminException)
539 assert thrown.message == 'Invalid list replacement'
542 @Sql([CLEAR_DATA, SET_DATA])
543 def 'Delete list scenario: #scenario.'() {
544 when: 'deleting list is executed for: #scenario.'
545 objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
546 and: 'remaining children are fetched'
547 def parentFragment = fragmentRepository.getById(parentFragmentId)
548 def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
549 then: 'only the expected children remain'
550 assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
551 assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
552 where: 'following parameters were used'
553 scenario | targetXpaths | parentFragmentId || expectedRemainingChildXpaths
554 'list element with key' | '/parent-203/child-204[@key="A"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ["/parent-203/child-203", "/parent-203/child-204[@key='B']"]
555 'list element with combined keys' | '/parent-202/child-205[@key="A" and @key2="B"]' | LIST_DATA_NODE_PARENT202_FRAGMENT_ID || ["/parent-202/child-206[@key='A']"]
556 'whole list' | '/parent-203/child-204' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203']
557 'list element under list element' | '/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
560 @Sql([CLEAR_DATA, SET_DATA])
561 def 'Delete multiple data nodes using scenario: #scenario.'() {
562 when: 'deleting nodes is executed for: #scenario.'
563 objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
564 and: 'remaining children are fetched'
565 def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT203_FRAGMENT_ID)
566 def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
567 then: 'only the expected children remain'
568 assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
569 assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
570 where: 'following parameters were used'
571 scenario | targetXpaths || expectedRemainingChildXpaths
572 'delete nothing' | [] || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
573 'datanode' | ['/parent-203/child-203'] || ["/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
574 '1 list element' | ['/parent-203/child-204[@key="A"]'] || ["/parent-203/child-203", "/parent-203/child-204[@key='B']"]
575 '2 list elements' | ['/parent-203/child-204[@key="A"]', '/parent-203/child-204[@key="B"]'] || ["/parent-203/child-203"]
576 'whole list' | ['/parent-203/child-204'] || ['/parent-203/child-203']
577 'list and element in same list' | ['/parent-203/child-204', '/parent-203/child-204[@key="A"]'] || ['/parent-203/child-203']
578 'list element under list element' | ['/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]'] || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
579 'invalid xpath' | ['INVALID XPATH', '/parent-203/child-204'] || ['/parent-203/child-203']
582 @Sql([CLEAR_DATA, SET_DATA])
583 def 'Delete multiple data nodes error scenario: #scenario.'() {
584 when: 'deleting nodes is executed for: #scenario.'
585 objectUnderTest.deleteDataNodes(dataspaceName, anchorName, targetXpaths)
586 then: 'a #expectedException is thrown'
587 thrown(expectedException)
588 where: 'the following data is used'
589 scenario | dataspaceName | anchorName | targetXpaths || expectedException
590 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | ['/not relevant'] || DataspaceNotFoundException
591 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | ['/not relevant'] || AnchorNotFoundException
592 'non-existing datanode' | DATASPACE_NAME | ANCHOR_NAME3 | ['/NON-EXISTING-XPATH'] || DataNodeNotFoundException
595 @Sql([CLEAR_DATA, SET_DATA])
596 def 'Delete data nodes with "/"-token in list key value: #scenario. (CPS-1409)'() {
597 given: 'a data nodes with list-element child with "/" in index value (and grandchild)'
598 def grandChild = new DataNodeBuilder().withXpath(deleteTestGrandChildXPath).build()
599 def child = new DataNodeBuilder().withXpath(deleteTestChildXpath).withChildDataNodes([grandChild]).build()
600 objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTestParentXPath, child)
601 and: 'number of children before delete is stored'
602 def numberOfChildrenBeforeDelete = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS)[0].childDataNodes.size()
603 when: 'target node is deleted'
604 objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTarget)
605 then: 'one child has been deleted'
606 def numberOfChildrenAfterDelete = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS)[0].childDataNodes.size()
607 assert numberOfChildrenAfterDelete == numberOfChildrenBeforeDelete - 1
609 scenario | deleteTarget | pathToParentOfDeletedNode
610 'list element with /' | deleteTestChildXpath | deleteTestParentXPath
611 'child of list element' | deleteTestGrandChildXPath | deleteTestChildXpath
614 @Sql([CLEAR_DATA, SET_DATA])
615 def 'Delete list error scenario: #scenario.'() {
616 when: 'attempting to delete scenario: #scenario.'
617 objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
618 then: 'a DataNodeNotFoundException is thrown'
619 thrown(DataNodeNotFoundException)
620 where: 'following parameters were used'
621 scenario | targetXpaths
622 'whole list, parent node does not exist' | '/unknown/some-child'
623 'list element, parent node does not exist' | '/unknown/child-204[@key="A"]'
624 'whole list does not exist' | '/parent-200/unknown'
625 'list element, list does not exist' | '/parent-200/unknown[@key="C"]'
626 'list element, element does not exist' | '/parent-203/child-204[@key="C"]'
627 'valid datanode but not a list' | '/parent-200/child-202'
630 @Sql([CLEAR_DATA, SET_DATA])
631 def 'Delete data node by xpath #scenario.'() {
632 given: 'a valid data node'
634 and: 'data nodes are deleted'
635 objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion)
636 when: 'verify data nodes are removed'
637 objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion, INCLUDE_ALL_DESCENDANTS)
639 thrown(DataNodeNotFoundException)
640 and: 'some related object is not deleted'
641 if (xpathSurvivor!=null) {
642 dataNode = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, xpathSurvivor, INCLUDE_ALL_DESCENDANTS)
643 assert dataNode[0].xpath == xpathSurvivor
645 where: 'following parameters were used'
646 scenario | xpathForDeletion || xpathSurvivor
647 'child data node, parent still exists' | '/parent-206/child-206' || '/parent-206'
648 'list element, sibling still exists' | '/parent-206/child-206/grand-child-206[@key="A"]' || "/parent-206/child-206/grand-child-206[@key='X']"
649 'container node' | '/parent-206' || null
650 'container list node' | '/parent-206[@key="A"]' || "/parent-206[@key='B']"
651 'root node with xpath /' | '/' || null
652 'root node with xpath passed as blank' | '' || null
655 @Sql([CLEAR_DATA, SET_DATA])
656 def 'Delete data node error scenario: #scenario.'() {
657 when: 'data node is deleted'
658 objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, datanodeXpath)
659 then: 'a #expectedException is thrown'
660 thrown(expectedException)
661 where: 'the following parameters were used'
662 scenario | datanodeXpath | expectedException
663 'valid data node, non existent child node' | '/parent-203/child-non-existent' | DataNodeNotFoundException
664 'invalid list element' | '/parent-206/child-206/grand-child-206@key="A"]' | CpsPathException
667 @Sql([CLEAR_DATA, SET_DATA])
668 def 'Delete data node for an anchor.'() {
669 given: 'a data-node exists for an anchor'
670 assert fragmentsExistInDB(3003)
671 when: 'data nodes are deleted '
672 objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3)
673 then: 'all data-nodes are deleted successfully'
674 assert !fragmentsExistInDB(3003)
677 @Sql([CLEAR_DATA, SET_DATA])
678 def 'Delete data node for multiple anchors.'() {
679 given: 'a data-node exists for an anchor'
680 assert fragmentsExistInDB(3001)
681 assert fragmentsExistInDB(3003)
682 when: 'data nodes are deleted '
683 objectUnderTest.deleteDataNodes(DATASPACE_NAME, ['ANCHOR-001', 'ANCHOR-003'])
684 then: 'all data-nodes are deleted successfully'
685 assert !fragmentsExistInDB(3001)
686 assert !fragmentsExistInDB(3003)
689 def fragmentsExistInDB(anchorId) {
690 fragmentRepository.existsByAnchorId(anchorId)
693 static Collection<DataNode> toDataNodes(xpaths) {
694 return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
698 static DataNode buildDataNode(xpath, leaves, childDataNodes) {
699 return dataNodeBuilder.withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
702 static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
703 return jsonObjectMapper.convertJsonString(fragmentEntity.attributes, Map<String, Object>.class)
706 def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
707 flatMap.put(dataNodeTree.xpath, dataNodeTree)
708 dataNodeTree.childDataNodes
709 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
713 def static multipleTreesToFlatMapByXpath(Map<String, DataNode> flatMap, Collection<DataNode> dataNodeTrees) {
714 for (DataNode dataNodeTree: dataNodeTrees){
715 flatMap.put(dataNodeTree.xpath, dataNodeTree)
716 dataNodeTree.childDataNodes
717 .forEach(childDataNode -> multipleTreesToFlatMapByXpath(flatMap, [childDataNode]))
722 def keysToXpaths(parent, Collection keys) {
723 return keys.collect { "${parent}/child-list[@key='${it}']".toString() }
726 def static createDataNodeTree(String... xpaths) {
727 def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
728 if (xpaths.length > 1) {
729 def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
730 def childDataNode = createDataNodeTree(xPathsDescendant)
731 dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
733 dataNodeBuilder.build()
736 def getFragmentByXpath(dataspaceName, anchorName, xpath) {
737 def dataspace = dataspaceRepository.getByName(dataspaceName)
738 def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
739 return fragmentRepository.findByAnchorAndXpath(anchor, xpath).orElseThrow()
742 def createChildListAllHavingAttributeValue(parentXpath, tag, Collection keys, boolean addGrandChild) {
743 def listElementAsDataNodes = keysToXpaths(parentXpath, keys).collect {
744 new DataNodeBuilder()
746 .withLeaves([attr1: tag])
750 listElementAsDataNodes.each {it.childDataNodes = [createGrandChild(it.xpath, tag)]}
752 return listElementAsDataNodes
755 def createGrandChild(parentXPath, tag) {
756 new DataNodeBuilder()
757 .withXpath("${parentXPath}/${tag}-grand-child")
758 .withLeaves([attr1: tag])