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