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