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