Merge "Added depth parameter in query nodes API."
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsDataPersistenceServiceIntegrationSpec.groovy
1 /*
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 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
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23 package org.onap.cps.spi.impl
24
25 import com.fasterxml.jackson.databind.ObjectMapper
26 import com.google.common.collect.ImmutableSet
27 import org.onap.cps.cpspath.parser.PathParsingException
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
41
42 import javax.validation.ConstraintViolationException
43
44 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
45 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
46
47 class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
48
49     @Autowired
50     CpsDataPersistenceService objectUnderTest
51
52     static JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
53     static DataNodeBuilder dataNodeBuilder = new DataNodeBuilder()
54
55     static final String SET_DATA = '/data/fragment.sql'
56     static int DATASPACE_1001_ID = 1001L
57     static int ANCHOR_3003_ID = 3003L
58     static long ID_DATA_NODE_WITH_DESCENDANTS = 4001
59     static String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
60     static String XPATH_DATA_NODE_WITH_LEAVES = '/parent-207'
61     static long DATA_NODE_202_FRAGMENT_ID = 4202L
62     static long CHILD_OF_DATA_NODE_202_FRAGMENT_ID = 4203L
63     static long LIST_DATA_NODE_PARENT201_FRAGMENT_ID = 4206L
64     static long LIST_DATA_NODE_PARENT203_FRAGMENT_ID = 4214L
65     static long LIST_DATA_NODE_PARENT202_FRAGMENT_ID = 4211L
66     static long PARENT_3_FRAGMENT_ID = 4003L
67
68     static Collection<DataNode> newDataNodes = [new DataNodeBuilder().build()]
69     static Collection<DataNode> existingDataNodes = [createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)]
70     static Collection<DataNode> existingChildDataNodes = [createDataNodeTree('/parent-1/child-1')]
71
72     def static deleteTestParentXPath = '/parent-200'
73     def static deleteTestChildXpath = "${deleteTestParentXPath}/child-with-slash[@key='a/b']"
74     def static deleteTestGrandChildXPath = "${deleteTestChildXpath}/grandChild"
75
76     def expectedLeavesByXpathMap = [
77             '/parent-207'                      : ['parent-leaf': 'parent-leaf value'],
78             '/parent-207/child-001'            : ['first-child-leaf': 'first-child-leaf value'],
79             '/parent-207/child-002'            : ['second-child-leaf': 'second-child-leaf value'],
80             '/parent-207/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
81     ]
82
83     @Sql([CLEAR_DATA, SET_DATA])
84     def 'Get existing datanode with descendants.'() {
85         when: 'the node is retrieved by its xpath'
86             def dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME1, '/parent-1', INCLUDE_ALL_DESCENDANTS)
87         then: 'the path and prefix are populated correctly'
88             assert dataNode.xpath == '/parent-1'
89         and: 'dataNode has no prefix (to be addressed by CPS-1301'
90             assert dataNode.moduleNamePrefix == null
91         and: 'the child node has the correct path'
92             assert dataNode.childDataNodes[0].xpath == '/parent-1/child-1'
93     }
94
95     @Sql([CLEAR_DATA, SET_DATA])
96     def 'Storing and Retrieving a new DataNodes with descendants.'() {
97         when: 'a fragment with descendants is stored'
98             def parentXpath = '/parent-new'
99             def childXpath = '/parent-new/child-new'
100             def grandChildXpath = '/parent-new/child-new/grandchild-new'
101             def dataNodes = [createDataNodeTree(parentXpath, childXpath, grandChildXpath)]
102             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, dataNodes)
103         then: 'it can be retrieved by its xpath'
104             def dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, INCLUDE_ALL_DESCENDANTS)
105             assert dataNode.xpath == parentXpath
106         and: 'it has the correct child'
107             assert dataNode.childDataNodes.size() == 1
108             def childDataNode = dataNode.childDataNodes[0]
109             assert childDataNode.xpath == childXpath
110         and: 'and its grandchild'
111             assert childDataNode.childDataNodes.size() == 1
112             def grandChildDataNode = childDataNode.childDataNodes[0]
113             assert grandChildDataNode.xpath == grandChildXpath
114     }
115
116     @Sql([CLEAR_DATA, SET_DATA])
117     def 'Store data node for multiple anchors using the same schema.'() {
118         def xpath = '/parent-new'
119         given: 'a fragment is stored for an anchor'
120             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, [createDataNodeTree(xpath)])
121         when: 'another fragment is stored for an other anchor, using the same schema set'
122             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME3, [createDataNodeTree(xpath)])
123         then: 'both fragments can be retrieved by their xpath'
124             def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
125             fragment1.anchor.name == ANCHOR_NAME1
126             fragment1.xpath == xpath
127             def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
128             fragment2.anchor.name == ANCHOR_NAME3
129             fragment2.xpath == xpath
130     }
131
132     @Sql([CLEAR_DATA, SET_DATA])
133     def 'Store datanodes error scenario: #scenario.'() {
134         when: 'attempt to store a data node with #scenario'
135             objectUnderTest.storeDataNodes(dataspaceName, anchorName, dataNodes)
136         then: 'a #expectedException is thrown'
137             thrown(expectedException)
138         where: 'the following data is used'
139             scenario                    | dataspaceName  | anchorName     | dataNodes          || expectedException
140             'dataspace does not exist'  | 'unknown'      | 'not-relevant' | newDataNodes       || DataspaceNotFoundException
141             'schema set does not exist' | DATASPACE_NAME | 'unknown'      | newDataNodes       || AnchorNotFoundException
142             'anchor already exists'     | DATASPACE_NAME | ANCHOR_NAME1   | newDataNodes       || ConstraintViolationException
143             'datanode already exists'   | DATASPACE_NAME | ANCHOR_NAME1   | existingDataNodes  || AlreadyDefinedExceptionBatch
144     }
145
146     @Sql([CLEAR_DATA, SET_DATA])
147     def 'Add children to a Fragment that already has a child.'() {
148         given: 'collection of new child data nodes'
149             def newChild1 = createDataNodeTree('/parent-1/child-2')
150             def newChild2 = createDataNodeTree('/parent-1/child-3')
151             def newChildrenCollection = [newChild1, newChild2]
152         when: 'the child is added to an existing parent with 1 child'
153             objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChildrenCollection)
154         then: 'the parent is now has to 3 children'
155             def expectedExistingChildPath = '/parent-1/child-1'
156             def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
157             parentFragment.childFragments.size() == 3
158         and: 'it still has the old child'
159             parentFragment.childFragments.find({ it.xpath == expectedExistingChildPath })
160         and: 'it has the new children'
161             parentFragment.childFragments.find({ it.xpath == newChildrenCollection[0].xpath })
162             parentFragment.childFragments.find({ it.xpath == newChildrenCollection[1].xpath })
163     }
164
165     @Sql([CLEAR_DATA, SET_DATA])
166     def 'Add child error scenario: #scenario.'() {
167         when: 'attempt to add a child data node with #scenario'
168             objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNodes)
169         then: 'a #expectedException is thrown'
170             thrown(expectedException)
171         where: 'the following data is used'
172             scenario                 | parentXpath                      | dataNodes               || expectedException
173             'parent does not exist'  | '/unknown'                       | newDataNodes            || DataNodeNotFoundException
174             'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNodes  || AlreadyDefinedExceptionBatch
175     }
176
177     @Sql([CLEAR_DATA, SET_DATA])
178     def 'Add collection of multiple new list elements including an element with a child datanode.'() {
179         given: 'two new child list elements for an existing parent'
180             def listElementXpaths = ['/parent-201/child-204[@key="NEW1"]', '/parent-201/child-204[@key="NEW2"]']
181             def listElements = toDataNodes(listElementXpaths)
182         and: 'a (grand)child data node for one of the new list elements'
183             def grandChild = buildDataNode('/parent-201/child-204[@key="NEW1"]/grand-child-204[@key2="NEW1-CHILD"]', [leave:'value'], [])
184             listElements[0].childDataNodes = [grandChild]
185         when: 'the new data node (list elements) are added to an existing parent node'
186             objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', [listElements])
187         then: 'new entries are successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
188             def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT201_FRAGMENT_ID)
189             def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
190             assert allChildXpaths.size() == 5
191             assert allChildXpaths.containsAll(listElementXpaths)
192         and: 'the (grand)child node of the new list entry is also present'
193             def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
194             def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_NAME3)
195             def grandChildFragmentEntity = fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, grandChild.xpath)
196             assert grandChildFragmentEntity.isPresent()
197     }
198
199     @Sql([CLEAR_DATA, SET_DATA])
200     def 'Add multiple list with a mix of existing and new elements'() {
201         given: 'two new child list elements for an existing parent'
202             def existingDataNode = dataNodeBuilder.withXpath('/parent-207/child-001').withLeaves(['id': '001']).build()
203             def newDataNode1 = dataNodeBuilder.withXpath('/parent-207/child-new1').withLeaves(['id': 'new1']).build()
204             def newDataNode2 = dataNodeBuilder.withXpath('/parent-200/child-new2').withLeaves(['id': 'new2']).build()
205             def dataNodeList1 = [existingDataNode, newDataNode1]
206             def dataNodeList2 = [newDataNode2]
207         when: 'duplicate data node is requested to be added'
208             objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT, '/', [dataNodeList1, dataNodeList2])
209         then: 'already defined batch exception is thrown'
210             def thrown = thrown(AlreadyDefinedExceptionBatch)
211         and: 'it only contains the xpath(s) of the duplicated elements'
212             assert thrown.alreadyDefinedXpaths.size() == 1
213             assert thrown.alreadyDefinedXpaths.contains('/parent-207/child-001')
214         and: 'it does NOT contains the xpaths of the new element that were not combined with existing elements'
215             assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
216             assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
217         and: 'the new entity is inserted correctly'
218             def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
219             def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT)
220             fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, '/parent-200/child-new2').isPresent()
221     }
222
223     @Sql([CLEAR_DATA, SET_DATA])
224     def 'Add list element error scenario: #scenario.'() {
225         given: 'list element as a collection of data nodes'
226             def listElements = toDataNodes(listElementXpaths)
227         when: 'attempt to add list elements to parent node'
228             objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listElements)
229         then: 'a #expectedException is thrown'
230             thrown(expectedException)
231         where: 'following parameters were used'
232             scenario                        | parentNodeXpath | listElementXpaths                   || expectedException
233             'parent node does not exist'    | '/unknown'      | ['irrelevant']                      || DataNodeNotFoundException
234             'data fragment already exists'  | '/parent-201'   | ["/parent-201/child-204[@key='A']"] || AlreadyDefinedExceptionBatch
235     }
236
237     @Sql([CLEAR_DATA, SET_DATA])
238     def 'Get data node by xpath without descendants.'() {
239         when: 'data node is requested'
240             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT,
241                     inputXPath, OMIT_DESCENDANTS)
242         then: 'data node is returned with no descendants'
243             assert result.xpath == XPATH_DATA_NODE_WITH_LEAVES
244         and: 'expected leaves'
245             assert result.childDataNodes.size() == 0
246             assertLeavesMaps(result.leaves, expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
247         where: 'the following data is used'
248             scenario      | inputXPath
249             'some xpath'  | '/parent-207'
250             'root xpath'  | '/'
251             'empty xpath' | ''
252     }
253
254     @Sql([CLEAR_DATA, SET_DATA])
255     def 'Cps Path query with syntax error throws a CPS Path Exception.'() {
256         when: 'trying to execute a query with a syntax (parsing) error'
257             objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, 'invalid-cps-path/child' , OMIT_DESCENDANTS)
258         then: 'exception is thrown'
259             def exceptionThrown = thrown(CpsPathException)
260             assert exceptionThrown.getDetails().contains('failed to parse at line 1 due to extraneous input \'invalid-cps-path\' expecting \'/\'')
261     }
262
263     @Sql([CLEAR_DATA, SET_DATA])
264     def 'Get data node by xpath with all descendants.'() {
265         when: 'data node is requested with all descendants'
266             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT,
267                     inputXPath, INCLUDE_ALL_DESCENDANTS)
268             def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
269         then: 'data node is returned with all the descendants populated'
270             assert mappedResult.size() == 4
271             assert result.childDataNodes.size() == 2
272             assert mappedResult.get('/parent-207/child-001').childDataNodes.size() == 0
273             assert mappedResult.get('/parent-207/child-002').childDataNodes.size() == 1
274         and: 'extracted leaves maps are matching expected'
275             mappedResult.forEach(
276                     (xPath, dataNode) -> assertLeavesMaps(dataNode.leaves, expectedLeavesByXpathMap[xPath]))
277         where: 'the following data is used'
278             scenario      | inputXPath
279             'some xpath'  | '/parent-207'
280             'root xpath'  | '/'
281             'empty xpath' | ''
282     }
283
284     @Sql([CLEAR_DATA, SET_DATA])
285     def 'Get data node error scenario: #scenario.'() {
286         when: 'attempt to get data node with #scenario'
287             objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
288         then: 'a #expectedException is thrown'
289             thrown(expectedException)
290         where: 'the following data is used'
291             scenario                 | dataspaceName  | anchorName                        | xpath           || expectedException
292             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | '/not relevant' || DataspaceNotFoundException
293             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | '/not relevant' || AnchorNotFoundException
294             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NO-XPATH'     || DataNodeNotFoundException
295             'invalid xpath'          | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH' || CpsPathException
296     }
297
298     @Sql([CLEAR_DATA, SET_DATA])
299     def 'Get multiple data nodes by xpath.'() {
300         when: 'fetch #scenario.'
301             def results = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, inputXpaths, OMIT_DESCENDANTS)
302         then: 'the expected number of data nodes are returned'
303             assert results.size() == expectedResultSize
304         where: 'following parameters were used'
305             scenario                               | inputXpaths                                     || expectedResultSize
306             '1 node'                               | ["/parent-200"]                                 || 1
307             '2 unique nodes'                       | ["/parent-200", "/parent-201"]                  || 2
308             '3 unique nodes'                       | ["/parent-200", "/parent-201", "/parent-202"]   || 3
309             '1 unique node with duplicate xpath'   | ["/parent-200", "/parent-200"]                  || 1
310             '2 unique nodes with duplicate xpath'  | ["/parent-200", "/parent-202", "/parent-200"]   || 2
311             'list element with key (single quote)' | ["/parent-201/child-204[@key='A']"]             || 1
312             'list element with key (double quote)' | ['/parent-201/child-204[@key="A"]']             || 1
313             'non-existing xpath'                   | ["/NO-XPATH"]                                   || 0
314             'existing and non-existing xpaths'     | ["/parent-200", "/NO-XPATH", "/parent-201"]     || 2
315             'invalid xpath'                        | ["INVALID XPATH"]                               || 0
316             'valid and invalid xpaths'             | ["/parent-200", "INVALID XPATH", "/parent-201"] || 2
317     }
318
319     @Sql([CLEAR_DATA, SET_DATA])
320     def 'Get multiple data nodes error scenario: #scenario.'() {
321         when: 'attempt to get data nodes with #scenario'
322             objectUnderTest.getDataNodes(dataspaceName, anchorName, ['/not-relevant'], OMIT_DESCENDANTS)
323         then: 'a #expectedException is thrown'
324             thrown(expectedException)
325         where: 'the following data is used'
326             scenario                 | dataspaceName  | anchorName     || expectedException
327             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' || DataspaceNotFoundException
328             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'    || AnchorNotFoundException
329     }
330
331     @Sql([CLEAR_DATA, SET_DATA])
332     def 'Update data node leaves.'() {
333         when: 'update is performed for leaves'
334             objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
335                     '/parent-200/child-201', ['leaf-value': 'new'])
336         then: 'leaves are updated for selected data node'
337             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
338             def updatedLeaves = getLeavesMap(updatedFragment)
339             assert updatedLeaves.size() == 1
340             assert updatedLeaves.'leaf-value' == 'new'
341         and: 'existing child entry remains as is'
342             def childFragment = updatedFragment.childFragments.iterator().next()
343             def childLeaves = getLeavesMap(childFragment)
344             assert childFragment.id == CHILD_OF_DATA_NODE_202_FRAGMENT_ID
345             assert childLeaves.'leaf-value' == 'original'
346     }
347
348     @Sql([CLEAR_DATA, SET_DATA])
349     def 'Update data leaves error scenario: #scenario.'() {
350         when: 'attempt to update data node for #scenario'
351             objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
352         then: 'a #expectedException is thrown'
353             thrown(expectedException)
354         where: 'the following data is used'
355             scenario                 | dataspaceName  | anchorName                        | xpath                 || expectedException
356             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | '/not relevant'       || DataspaceNotFoundException
357             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | '/not relevant'       || AnchorNotFoundException
358             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
359     }
360
361     @Sql([CLEAR_DATA, SET_DATA])
362     def 'Update data node and descendants by removing descendants.'() {
363         given: 'data node object with leaves updated, no children'
364             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [])
365         when: 'update data nodes and descendants is performed'
366             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
367         then: 'leaves have been updated for selected data node'
368             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
369             def updatedLeaves = getLeavesMap(updatedFragment)
370             assert updatedLeaves.size() == 1
371             assert updatedLeaves.'leaf-value' == 'new'
372         and: 'updated entry has no children'
373             updatedFragment.childFragments.isEmpty()
374         and: 'previously attached child entry is removed from database'
375             fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
376     }
377
378     @Sql([CLEAR_DATA, SET_DATA])
379     def 'Update data node and descendants with new descendants'() {
380         given: 'data node object with leaves updated, having child with old content'
381             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
382                   buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'original'], [])
383             ])
384         when: 'update is performed including descendants'
385             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
386         then: 'leaves have been updated for selected data node'
387             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
388             def updatedLeaves = getLeavesMap(updatedFragment)
389             assert updatedLeaves.size() == 1
390             assert updatedLeaves.'leaf-value' == 'new'
391         and: 'existing child entry is not updated as content is same'
392             def childFragment = updatedFragment.childFragments.iterator().next()
393             childFragment.xpath == '/parent-200/child-201/grand-child'
394             def childLeaves = getLeavesMap(childFragment)
395             assert childLeaves.'leaf-value' == 'original'
396     }
397
398     @Sql([CLEAR_DATA, SET_DATA])
399     def 'Update data node and descendants with same descendants but changed leaf value.'() {
400         given: 'data node object with leaves updated, having child with old content'
401             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
402                     buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'new'], [])
403             ])
404         when: 'update is performed including descendants'
405             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
406         then: 'leaves have been updated for selected data node'
407             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
408             def updatedLeaves = getLeavesMap(updatedFragment)
409             assert updatedLeaves.size() == 1
410             assert updatedLeaves.'leaf-value' == 'new'
411         and: 'existing child entry is updated with the new content'
412             def childFragment = updatedFragment.childFragments.iterator().next()
413             childFragment.xpath == '/parent-200/child-201/grand-child'
414             def childLeaves = getLeavesMap(childFragment)
415             assert childLeaves.'leaf-value' == 'new'
416     }
417
418     @Sql([CLEAR_DATA, SET_DATA])
419     def 'Update data node and descendants with different descendants xpath'() {
420         given: 'data node object with leaves updated, having child with old content'
421             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
422                     buildDataNode('/parent-200/child-201/grand-child-new', ['leaf-value': 'new'], [])
423             ])
424         when: 'update is performed including descendants'
425             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
426         then: 'leaves have been updated for selected data node'
427             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
428             def updatedLeaves = getLeavesMap(updatedFragment)
429             assert updatedLeaves.size() == 1
430             assert updatedLeaves.'leaf-value' == 'new'
431         and: 'previously attached child entry is removed from database'
432             fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
433         and: 'new child entry is persisted'
434             def childFragment = updatedFragment.childFragments.iterator().next()
435             childFragment.xpath == '/parent-200/child-201/grand-child-new'
436             def childLeaves = getLeavesMap(childFragment)
437             assert childLeaves.'leaf-value' == 'new'
438     }
439
440     @Sql([CLEAR_DATA, SET_DATA])
441     def 'Update data node and descendants error scenario: #scenario.'() {
442         given: 'data node object'
443             def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
444         when: 'attempt to update data node for #scenario'
445             objectUnderTest.updateDataNodeAndDescendants(dataspaceName, anchorName, submittedDataNode)
446         then: 'a #expectedException is thrown'
447             thrown(expectedException)
448         where: 'the following data is used'
449             scenario                 | dataspaceName  | anchorName                        | xpath                 || expectedException
450             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | '/not relevant'       || DataspaceNotFoundException
451             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | '/not relevant'       || AnchorNotFoundException
452             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
453             'invalid xpath'          | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH'       || CpsPathException
454     }
455
456     @Sql([CLEAR_DATA, SET_DATA])
457     def 'Update existing list with #scenario.'() {
458         given: 'a parent having a list of data nodes containing: #originalKeys (ech list element has a child too)'
459             def parentXpath = '/parent-3'
460             if (originalKeys.size() > 0) {
461                 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'original value', originalKeys, true)
462                 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
463             }
464         and: 'each original list element has one child'
465             def originalParentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
466             originalParentFragment.childFragments.each {assert it.childFragments.size() == 1 }
467         when: 'it is updated with #scenario'
468             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new value', replacementKeys, false)
469             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
470         then: 'the result list ONLY contains the expected replacement elements'
471             def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
472             def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
473             def expectedListEntriesAfterUpdateAsXpaths = keysToXpaths(parentXpath, replacementKeys)
474             assert allChildXpaths.size() == replacementKeys.size()
475             assert allChildXpaths.containsAll(expectedListEntriesAfterUpdateAsXpaths)
476         and: 'all the list elements have the new values'
477             assert parentFragment.childFragments.stream().allMatch(childFragment -> childFragment.attributes.contains('new value'))
478         and: 'there are no more grandchildren as none of the replacement list entries had a child'
479             parentFragment.childFragments.each {assert it.childFragments.size() == 0 }
480         where: 'the following replacement lists are applied'
481             scenario                                            | originalKeys | replacementKeys
482             'one existing entry only'                           | []           | ['NEW']
483             'multiple new entries'                              | []           | ['NEW1', 'NEW2']
484             'one new entry only (existing entries are deleted)' | ['A', 'B']   | ['NEW1', 'NEW2']
485             'one existing on new entry'                         | ['A', 'B']   | ['A', 'NEW']
486             'one existing entry only'                           | ['A', 'B']   | ['A']
487     }
488
489     @Sql([CLEAR_DATA, SET_DATA])
490     def 'Replacing existing list element with attributes and (grand)child.'() {
491         given: 'a parent with list elements A and B with attribute and grandchild tagged as "org"'
492             def parentXpath = '/parent-3'
493             def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'org', ['A','B'], true)
494             objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
495         when: 'A is replaced with an entry with attribute and grandchild tagged tagged as "new" (B is not in replacement list)'
496             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new', ['A'], true)
497             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
498         then: 'The updated fragment has a child-list with ONLY element "A"'
499             def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
500             parentFragment.childFragments.size() == 1
501             def childListElementA = parentFragment.childFragments[0]
502             childListElementA.xpath == "/parent-3/child-list[@key='A']"
503         and: 'element "A" has an attribute with the "new" (tag) value'
504             childListElementA.attributes == '{"attr1": "new"}'
505         and: 'element "A" has a only one (grand)child'
506             childListElementA.childFragments.size() == 1
507         and: 'the grandchild is the new grandchild (tag)'
508             def grandChild = childListElementA.childFragments[0]
509             grandChild.xpath == "/parent-3/child-list[@key='A']/new-grand-child"
510         and: 'the grandchild has an attribute with the "new" (tag) value'
511             grandChild.attributes == '{"attr1": "new"}'
512     }
513
514     @Sql([CLEAR_DATA, SET_DATA])
515     def 'Replace list element for a parent (parent-1) with existing one (non-list) child'() {
516         when: 'a list element is added under the parent'
517             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(XPATH_DATA_NODE_WITH_DESCENDANTS, 'new', ['A','B'], false)
518             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, replacementListEntriesAsDataNodes)
519         then: 'the parent will have 3 children after the replacement'
520             def parentFragment = fragmentRepository.getById(ID_DATA_NODE_WITH_DESCENDANTS)
521             parentFragment.childFragments.size() == 3
522             def xpaths = parentFragment.childFragments.collect {it.xpath}
523         and: 'one of the children is the original child fragment'
524             xpaths.contains('/parent-1/child-1')
525         and: 'it has the two new list elements'
526             xpaths.containsAll("/parent-1/child-list[@key='A']", "/parent-1/child-list[@key='B']")
527     }
528
529     @Sql([CLEAR_DATA, SET_DATA])
530     def 'Replace list content using unknown parent'() {
531         given: 'list element as a collection of data nodes'
532             def listElementCollection = toDataNodes(['irrelevant'])
533         when: 'attempt to replace list elements under unknown parent node'
534             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/unknown', listElementCollection)
535         then: 'a datanode not found exception is thrown'
536             thrown(DataNodeNotFoundException)
537     }
538
539     @Sql([CLEAR_DATA, SET_DATA])
540     def 'Replace list content with empty collection is not supported'() {
541         when: 'attempt to replace list elements with empty collection'
542             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/parent-203', [])
543         then: 'a CPS admin exception is thrown'
544             def thrown = thrown(CpsAdminException)
545             assert thrown.message == 'Invalid list replacement'
546     }
547
548     @Sql([CLEAR_DATA, SET_DATA])
549     def 'Delete list scenario: #scenario.'() {
550         when: 'deleting list is executed for: #scenario.'
551             objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
552         then: 'only the expected children remain'
553             def parentFragment = fragmentRepository.getById(parentFragmentId)
554             def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
555             assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
556             assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
557         where: 'following parameters were used'
558             scenario                          | targetXpaths                                                 | parentFragmentId                     || expectedRemainingChildXpaths
559             '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']"]
560             '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']"]
561             'whole list'                      | '/parent-203/child-204'                                      | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203']
562             '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']"]
563     }
564
565     @Sql([CLEAR_DATA, SET_DATA])
566     def 'Delete data nodes with "/"-token in list key value: #scenario. (CPS-1409)'() {
567         given: 'a data nodes with list-element child with "/" in index value (and grandchild)'
568             def grandChild = new DataNodeBuilder().withXpath(deleteTestGrandChildXPath).build()
569             def child = new DataNodeBuilder().withXpath(deleteTestChildXpath).withChildDataNodes([grandChild]).build()
570             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTestParentXPath, child)
571         and: 'number of children before delete is stored'
572             def numberOfChildrenBeforeDelete = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS).childDataNodes.size()
573         when: 'target node is deleted'
574             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTarget)
575         then: 'one child has been deleted'
576             def numberOfChildrenAfterDelete = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS).childDataNodes.size()
577             assert numberOfChildrenAfterDelete == numberOfChildrenBeforeDelete - 1
578         where:
579             scenario                | deleteTarget              | pathToParentOfDeletedNode
580             'list element with /'   | deleteTestChildXpath      | deleteTestParentXPath
581             'child of list element' | deleteTestGrandChildXPath | deleteTestChildXpath
582     }
583
584     @Sql([CLEAR_DATA, SET_DATA])
585     def 'Delete list error scenario: #scenario.'() {
586         when: 'attempting to delete scenario: #scenario.'
587             objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
588         then: 'a DataNodeNotFoundException is thrown'
589             thrown(DataNodeNotFoundException)
590         where: 'following parameters were used'
591             scenario                                   | targetXpaths
592             'whole list, parent node does not exist'   | '/unknown/some-child'
593             'list element, parent node does not exist' | '/unknown/child-204[@key="A"]'
594             'whole list does not exist'                | '/parent-200/unknown'
595             'list element, list does not exist'        | '/parent-200/unknown[@key="C"]'
596             'list element, element does not exist'     | '/parent-203/child-204[@key="C"]'
597             'valid datanode but not a list'            | '/parent-200/child-202'
598     }
599
600     @Sql([CLEAR_DATA, SET_DATA])
601     def 'Delete data node by xpath #scenario.'() {
602         given: 'a valid data node'
603             def dataNode
604         and: 'data nodes are deleted'
605             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion)
606         when: 'verify data nodes are removed'
607             objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion, INCLUDE_ALL_DESCENDANTS)
608         then:
609             thrown(DataNodeNotFoundException)
610         and: 'some related object is not deleted'
611             if (xpathSurvivor!=null) {
612                 dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathSurvivor, INCLUDE_ALL_DESCENDANTS)
613                 assert dataNode.xpath == xpathSurvivor
614             }
615         where: 'following parameters were used'
616             scenario                               | xpathForDeletion                                  || xpathSurvivor
617             'child data node, parent still exists' | '/parent-206/child-206'                           || '/parent-206'
618             'list element, sibling still exists'   | '/parent-206/child-206/grand-child-206[@key="A"]' || "/parent-206/child-206/grand-child-206[@key='X']"
619             'container node'                       | '/parent-206'                                     || null
620             'container list node'                  | '/parent-206[@key="A"]'                           || "/parent-206[@key='B']"
621             'root node with xpath /'               | '/'                                               || null
622             'root node with xpath passed as blank' | ''                                                || null
623     }
624
625     @Sql([CLEAR_DATA, SET_DATA])
626     def 'Delete data node error scenario: #scenario.'() {
627         when: 'data node is deleted'
628             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, datanodeXpath)
629         then: 'a #expectedException is thrown'
630             thrown(expectedException)
631         where: 'the following parameters were used'
632             scenario                                        | datanodeXpath                                    | expectedException
633             'valid data node, non existent child node'      | '/parent-203/child-non-existent'                 | DataNodeNotFoundException
634             'invalid list element'                          | '/parent-206/child-206/grand-child-206@key="A"]' | PathParsingException
635     }
636
637     @Sql([CLEAR_DATA, SET_DATA])
638     def 'Delete data node for an anchor.'() {
639         given: 'a data-node exists for an anchor'
640             assert fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
641         when: 'data nodes are deleted '
642             objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3)
643         then: 'all data-nodes are deleted successfully'
644             assert !fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
645     }
646
647     def fragmentsExistInDB(dataSpaceId, anchorId) {
648         !fragmentRepository.findRootsByDataspaceAndAnchor(dataSpaceId, anchorId).isEmpty()
649     }
650
651     static Collection<DataNode> toDataNodes(xpaths) {
652         return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
653     }
654
655
656     static DataNode buildDataNode(xpath, leaves, childDataNodes) {
657         return dataNodeBuilder.withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
658     }
659
660     static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
661         return jsonObjectMapper.convertJsonString(fragmentEntity.attributes, Map<String, Object>.class)
662     }
663
664     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
665         expectedLeavesMap.forEach((key, value) -> {
666             def actualValue = actualLeavesMap[key]
667             if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
668                 assert value.size() == actualValue.size()
669                 assert value.containsAll(actualValue)
670             } else {
671                 assert value == actualValue
672             }
673         })
674         return true
675     }
676
677     def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
678         flatMap.put(dataNodeTree.xpath, dataNodeTree)
679         dataNodeTree.childDataNodes
680                 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
681         return flatMap
682     }
683
684     def keysToXpaths(parent, Collection keys) {
685         return keys.collect { "${parent}/child-list[@key='${it}']".toString() }
686     }
687
688     def static createDataNodeTree(String... xpaths) {
689         def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
690         if (xpaths.length > 1) {
691             def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
692             def childDataNode = createDataNodeTree(xPathsDescendant)
693             dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
694         }
695         dataNodeBuilder.build()
696     }
697
698     def getFragmentByXpath(dataspaceName, anchorName, xpath) {
699         def dataspace = dataspaceRepository.getByName(dataspaceName)
700         def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
701         return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
702     }
703
704
705     def createChildListAllHavingAttributeValue(parentXpath, tag, Collection keys, boolean addGrandChild) {
706         def listElementAsDataNodes = keysToXpaths(parentXpath, keys).collect {
707                 new DataNodeBuilder()
708                     .withXpath(it)
709                     .withLeaves([attr1: tag])
710                     .build()
711         }
712         if (addGrandChild) {
713             listElementAsDataNodes.each {it.childDataNodes = [createGrandChild(it.xpath, tag)]}
714         }
715         return listElementAsDataNodes
716     }
717
718     def createGrandChild(parentXPath, tag) {
719         new DataNodeBuilder()
720             .withXpath("${parentXPath}/${tag}-grand-child")
721             .withLeaves([attr1: tag])
722             .build()
723     }
724
725 }