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 * Modifications Copyright (C) 2022 TechMahindra Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
23 package org.onap.cps.spi.impl
25 import com.fasterxml.jackson.databind.ObjectMapper
26 import com.google.common.collect.ImmutableSet
27 import org.onap.cps.cpspath.parser.PathParsingException
28 import org.onap.cps.spi.CpsDataPersistenceService
29 import org.onap.cps.spi.entities.FragmentEntity
30 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch
31 import org.onap.cps.spi.exceptions.AnchorNotFoundException
32 import org.onap.cps.spi.exceptions.CpsAdminException
33 import org.onap.cps.spi.exceptions.CpsPathException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
36 import org.onap.cps.spi.model.DataNode
37 import org.onap.cps.spi.model.DataNodeBuilder
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.springframework.beans.factory.annotation.Autowired
40 import org.springframework.test.context.jdbc.Sql
41 import javax.validation.ConstraintViolationException
43 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
44 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
46 class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
49 CpsDataPersistenceService objectUnderTest
51 static JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
52 static DataNodeBuilder dataNodeBuilder = new DataNodeBuilder()
54 static final String SET_DATA = '/data/fragment.sql'
55 static int DATASPACE_1001_ID = 1001L
56 static int ANCHOR_3003_ID = 3003L
57 static long ID_DATA_NODE_WITH_DESCENDANTS = 4001
58 static String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
59 static String XPATH_DATA_NODE_WITH_LEAVES = '/parent-207'
60 static long DATA_NODE_202_FRAGMENT_ID = 4202L
61 static long CHILD_OF_DATA_NODE_202_FRAGMENT_ID = 4203L
62 static long LIST_DATA_NODE_PARENT201_FRAGMENT_ID = 4206L
63 static long LIST_DATA_NODE_PARENT203_FRAGMENT_ID = 4214L
64 static long LIST_DATA_NODE_PARENT202_FRAGMENT_ID = 4211L
65 static long PARENT_3_FRAGMENT_ID = 4003L
67 static Collection<DataNode> newDataNodes = [new DataNodeBuilder().build()]
68 static Collection<DataNode> existingDataNodes = [createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)]
69 static Collection<DataNode> existingChildDataNodes = [createDataNodeTree('/parent-1/child-1')]
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']
78 @Sql([CLEAR_DATA, SET_DATA])
79 def 'Get existing datanode with descendants.'() {
80 when: 'the node is retrieved by its xpath'
81 def dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME1, '/parent-1', INCLUDE_ALL_DESCENDANTS)
82 then: 'the path and prefix are populated correctly'
83 assert dataNode.xpath == '/parent-1'
84 and: 'dataNode has no prefix (to be addressed by CPS-1301'
85 assert dataNode.moduleNamePrefix == null
86 and: 'the child node has the correct path'
87 assert dataNode.childDataNodes[0].xpath == '/parent-1/child-1'
90 @Sql([CLEAR_DATA, SET_DATA])
91 def 'Storing and Retrieving a new DataNodes with descendants.'() {
92 when: 'a fragment with descendants is stored'
93 def parentXpath = '/parent-new'
94 def childXpath = '/parent-new/child-new'
95 def grandChildXpath = '/parent-new/child-new/grandchild-new'
96 def dataNodes = [createDataNodeTree(parentXpath, childXpath, grandChildXpath)]
97 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, dataNodes)
98 then: 'it can be retrieved by its xpath'
99 def dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, INCLUDE_ALL_DESCENDANTS)
100 assert dataNode.xpath == parentXpath
101 and: 'it has the correct child'
102 assert dataNode.childDataNodes.size() == 1
103 def childDataNode = dataNode.childDataNodes[0]
104 assert childDataNode.xpath == childXpath
105 and: 'and its grandchild'
106 assert childDataNode.childDataNodes.size() == 1
107 def grandChildDataNode = childDataNode.childDataNodes[0]
108 assert grandChildDataNode.xpath == grandChildXpath
111 @Sql([CLEAR_DATA, SET_DATA])
112 def 'Store data node for multiple anchors using the same schema.'() {
113 def xpath = '/parent-new'
114 given: 'a fragment is stored for an anchor'
115 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, [createDataNodeTree(xpath)])
116 when: 'another fragment is stored for an other anchor, using the same schema set'
117 objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME3, [createDataNodeTree(xpath)])
118 then: 'both fragments can be retrieved by their xpath'
119 def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
120 fragment1.anchor.name == ANCHOR_NAME1
121 fragment1.xpath == xpath
122 def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
123 fragment2.anchor.name == ANCHOR_NAME3
124 fragment2.xpath == xpath
127 @Sql([CLEAR_DATA, SET_DATA])
128 def 'Store datanodes error scenario: #scenario.'() {
129 when: 'attempt to store a data node with #scenario'
130 objectUnderTest.storeDataNodes(dataspaceName, anchorName, dataNodes)
131 then: 'a #expectedException is thrown'
132 thrown(expectedException)
133 where: 'the following data is used'
134 scenario | dataspaceName | anchorName | dataNodes || expectedException
135 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNodes || DataspaceNotFoundException
136 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNodes || AnchorNotFoundException
137 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNodes || ConstraintViolationException
138 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNodes || AlreadyDefinedExceptionBatch
141 @Sql([CLEAR_DATA, SET_DATA])
142 def 'Add children to a Fragment that already has a child.'() {
143 given: 'collection of new child data nodes'
144 def newChild1 = createDataNodeTree('/parent-1/child-2')
145 def newChild2 = createDataNodeTree('/parent-1/child-3')
146 def newChildrenCollection = [newChild1, newChild2]
147 when: 'the child is added to an existing parent with 1 child'
148 objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChildrenCollection)
149 then: 'the parent is now has to 3 children'
150 def expectedExistingChildPath = '/parent-1/child-1'
151 def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
152 parentFragment.childFragments.size() == 3
153 and: 'it still has the old child'
154 parentFragment.childFragments.find({ it.xpath == expectedExistingChildPath })
155 and: 'it has the new children'
156 parentFragment.childFragments.find({ it.xpath == newChildrenCollection[0].xpath })
157 parentFragment.childFragments.find({ it.xpath == newChildrenCollection[1].xpath })
160 @Sql([CLEAR_DATA, SET_DATA])
161 def 'Add child error scenario: #scenario.'() {
162 when: 'attempt to add a child data node with #scenario'
163 objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNodes)
164 then: 'a #expectedException is thrown'
165 thrown(expectedException)
166 where: 'the following data is used'
167 scenario | parentXpath | dataNodes || expectedException
168 'parent does not exist' | '/unknown' | newDataNodes || DataNodeNotFoundException
169 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNodes || AlreadyDefinedExceptionBatch
172 @Sql([CLEAR_DATA, SET_DATA])
173 def 'Add collection of multiple new list elements including an element with a child datanode.'() {
174 given: 'two new child list elements for an existing parent'
175 def listElementXpaths = ['/parent-201/child-204[@key="NEW1"]', '/parent-201/child-204[@key="NEW2"]']
176 def listElements = toDataNodes(listElementXpaths)
177 and: 'a (grand)child data node for one of the new list elements'
178 def grandChild = buildDataNode('/parent-201/child-204[@key="NEW1"]/grand-child-204[@key2="NEW1-CHILD"]', [leave:'value'], [])
179 listElements[0].childDataNodes = [grandChild]
180 when: 'the new data node (list elements) are added to an existing parent node'
181 objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', [listElements])
182 then: 'new entries are successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
183 def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT201_FRAGMENT_ID)
184 def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
185 assert allChildXpaths.size() == 5
186 assert allChildXpaths.containsAll(listElementXpaths)
187 and: 'the (grand)child node of the new list entry is also present'
188 def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
189 def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_NAME3)
190 def grandChildFragmentEntity = fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, grandChild.xpath)
191 assert grandChildFragmentEntity.isPresent()
194 @Sql([CLEAR_DATA, SET_DATA])
195 def 'Add multiple list with a mix of existing and new elements'() {
196 given: 'two new child list elements for an existing parent'
197 def existingDataNode = dataNodeBuilder.withXpath('/parent-207/child-001').withLeaves(['id': '001']).build()
198 def newDataNode1 = dataNodeBuilder.withXpath('/parent-207/child-new1').withLeaves(['id': 'new1']).build()
199 def newDataNode2 = dataNodeBuilder.withXpath('/parent-200/child-new2').withLeaves(['id': 'new2']).build()
200 def dataNodeList1 = [existingDataNode, newDataNode1]
201 def dataNodeList2 = [newDataNode2]
202 when: 'duplicate data node is requested to be added'
203 objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT, '/', [dataNodeList1, dataNodeList2])
204 then: 'already defined batch exception is thrown'
205 def thrown = thrown(AlreadyDefinedExceptionBatch)
206 and: 'it only contains the xpath(s) of the duplicated elements'
207 assert thrown.alreadyDefinedXpaths.size() == 1
208 assert thrown.alreadyDefinedXpaths.contains('/parent-207/child-001')
209 and: 'it does NOT contains the xpaths of the new element that were not combined with existing elements'
210 assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
211 assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
212 and: 'the new entity is inserted correctly'
213 def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
214 def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT)
215 fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, '/parent-200/child-new2').isPresent()
218 @Sql([CLEAR_DATA, SET_DATA])
219 def 'Add list element error scenario: #scenario.'() {
220 given: 'list element as a collection of data nodes'
221 def listElements = toDataNodes(listElementXpaths)
222 when: 'attempt to add list elements to parent node'
223 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listElements)
224 then: 'a #expectedException is thrown'
225 thrown(expectedException)
226 where: 'following parameters were used'
227 scenario | parentNodeXpath | listElementXpaths || expectedException
228 'parent node does not exist' | '/unknown' | ['irrelevant'] || DataNodeNotFoundException
229 'data fragment already exists' | '/parent-201' | ["/parent-201/child-204[@key='A']"] || AlreadyDefinedExceptionBatch
232 @Sql([CLEAR_DATA, SET_DATA])
233 def 'Get data node by xpath without descendants.'() {
234 when: 'data node is requested'
235 def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT,
236 inputXPath, OMIT_DESCENDANTS)
237 then: 'data node is returned with no descendants'
238 assert result.xpath == XPATH_DATA_NODE_WITH_LEAVES
239 and: 'expected leaves'
240 assert result.childDataNodes.size() == 0
241 assertLeavesMaps(result.leaves, expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
242 where: 'the following data is used'
243 scenario | inputXPath
244 'some xpath' | '/parent-207'
249 @Sql([CLEAR_DATA, SET_DATA])
250 def 'Cps Path query with syntax error throws a CPS Path Exception.'() {
251 when: 'trying to execute a query with a syntax (parsing) error'
252 objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, 'invalid-cps-path/child' , OMIT_DESCENDANTS)
253 then: 'exception is thrown'
254 def exceptionThrown = thrown(CpsPathException)
255 assert exceptionThrown.getDetails().contains('failed to parse at line 1 due to extraneous input \'invalid-cps-path\' expecting \'/\'')
258 @Sql([CLEAR_DATA, SET_DATA])
259 def 'Get data node by xpath with all descendants.'() {
260 when: 'data node is requested with all descendants'
261 def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT,
262 inputXPath, INCLUDE_ALL_DESCENDANTS)
263 def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
264 then: 'data node is returned with all the descendants populated'
265 assert mappedResult.size() == 4
266 assert result.childDataNodes.size() == 2
267 assert mappedResult.get('/parent-207/child-001').childDataNodes.size() == 0
268 assert mappedResult.get('/parent-207/child-002').childDataNodes.size() == 1
269 and: 'extracted leaves maps are matching expected'
270 mappedResult.forEach(
271 (xPath, dataNode) -> assertLeavesMaps(dataNode.leaves, expectedLeavesByXpathMap[xPath]))
272 where: 'the following data is used'
273 scenario | inputXPath
274 'some xpath' | '/parent-207'
279 @Sql([CLEAR_DATA, SET_DATA])
280 def 'Get data node error scenario: #scenario.'() {
281 when: 'attempt to get data node with #scenario'
282 objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
283 then: 'a #expectedException is thrown'
284 thrown(expectedException)
285 where: 'the following data is used'
286 scenario | dataspaceName | anchorName | xpath || expectedException
287 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | '/not relevant' || DataspaceNotFoundException
288 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | '/not relevant' || AnchorNotFoundException
289 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NO XPATH' || DataNodeNotFoundException
292 @Sql([CLEAR_DATA, SET_DATA])
293 def 'Update data node leaves.'() {
294 when: 'update is performed for leaves'
295 objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
296 '/parent-200/child-201', ['leaf-value': 'new'])
297 then: 'leaves are updated for selected data node'
298 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
299 def updatedLeaves = getLeavesMap(updatedFragment)
300 assert updatedLeaves.size() == 1
301 assert updatedLeaves.'leaf-value' == 'new'
302 and: 'existing child entry remains as is'
303 def childFragment = updatedFragment.childFragments.iterator().next()
304 def childLeaves = getLeavesMap(childFragment)
305 assert childFragment.id == CHILD_OF_DATA_NODE_202_FRAGMENT_ID
306 assert childLeaves.'leaf-value' == 'original'
309 @Sql([CLEAR_DATA, SET_DATA])
310 def 'Update data leaves error scenario: #scenario.'() {
311 when: 'attempt to update data node for #scenario'
312 objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
313 then: 'a #expectedException is thrown'
314 thrown(expectedException)
315 where: 'the following data is used'
316 scenario | dataspaceName | anchorName | xpath || expectedException
317 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | '/not relevant' || DataspaceNotFoundException
318 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | '/not relevant' || AnchorNotFoundException
319 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING XPATH' || DataNodeNotFoundException
322 @Sql([CLEAR_DATA, SET_DATA])
323 def 'Update data node and descendants by removing descendants.'() {
324 given: 'data node object with leaves updated, no children'
325 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [])
326 when: 'update data nodes and descendants is performed'
327 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
328 then: 'leaves have been updated for selected data node'
329 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
330 def updatedLeaves = getLeavesMap(updatedFragment)
331 assert updatedLeaves.size() == 1
332 assert updatedLeaves.'leaf-value' == 'new'
333 and: 'updated entry has no children'
334 updatedFragment.childFragments.isEmpty()
335 and: 'previously attached child entry is removed from database'
336 fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
339 @Sql([CLEAR_DATA, SET_DATA])
340 def 'Update data node and descendants with new descendants'() {
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': 'original'], [])
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 not updated as content is same'
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' == 'original'
359 @Sql([CLEAR_DATA, SET_DATA])
360 def 'Update data node and descendants with same descendants but changed leaf value.'() {
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', ['leaf-value': 'new'], [])
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: 'existing child entry is updated with the new content'
373 def childFragment = updatedFragment.childFragments.iterator().next()
374 childFragment.xpath == '/parent-200/child-201/grand-child'
375 def childLeaves = getLeavesMap(childFragment)
376 assert childLeaves.'leaf-value' == 'new'
379 @Sql([CLEAR_DATA, SET_DATA])
380 def 'Update data node and descendants with different descendants xpath'() {
381 given: 'data node object with leaves updated, having child with old content'
382 def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
383 buildDataNode('/parent-200/child-201/grand-child-new', ['leaf-value': 'new'], [])
385 when: 'update is performed including descendants'
386 objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
387 then: 'leaves have been updated for selected data node'
388 def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
389 def updatedLeaves = getLeavesMap(updatedFragment)
390 assert updatedLeaves.size() == 1
391 assert updatedLeaves.'leaf-value' == 'new'
392 and: 'previously attached child entry is removed from database'
393 fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
394 and: 'new child entry is persisted'
395 def childFragment = updatedFragment.childFragments.iterator().next()
396 childFragment.xpath == '/parent-200/child-201/grand-child-new'
397 def childLeaves = getLeavesMap(childFragment)
398 assert childLeaves.'leaf-value' == 'new'
401 @Sql([CLEAR_DATA, SET_DATA])
402 def 'Update data node and descendants error scenario: #scenario.'() {
403 given: 'data node object'
404 def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
405 when: 'attempt to update data node for #scenario'
406 objectUnderTest.updateDataNodeAndDescendants(dataspaceName, anchorName, submittedDataNode)
407 then: 'a #expectedException is thrown'
408 thrown(expectedException)
409 where: 'the following data is used'
410 scenario | dataspaceName | anchorName | xpath || expectedException
411 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | '/not relevant' || DataspaceNotFoundException
412 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | '/not relevant' || AnchorNotFoundException
413 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING XPATH' || DataNodeNotFoundException
416 @Sql([CLEAR_DATA, SET_DATA])
417 def 'Update existing list with #scenario.'() {
418 given: 'a parent having a list of data nodes containing: #originalKeys (ech list element has a child too)'
419 def parentXpath = '/parent-3'
420 if (originalKeys.size() > 0) {
421 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'original value', originalKeys, true)
422 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
424 and: 'each original list element has one child'
425 def originalParentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
426 originalParentFragment.childFragments.each {assert it.childFragments.size() == 1 }
427 when: 'it is updated with #scenario'
428 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new value', replacementKeys, false)
429 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
430 then: 'the result list ONLY contains the expected replacement elements'
431 def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
432 def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
433 def expectedListEntriesAfterUpdateAsXpaths = keysToXpaths(parentXpath, replacementKeys)
434 assert allChildXpaths.size() == replacementKeys.size()
435 assert allChildXpaths.containsAll(expectedListEntriesAfterUpdateAsXpaths)
436 and: 'all the list elements have the new values'
437 assert parentFragment.childFragments.stream().allMatch(childFragment -> childFragment.attributes.contains('new value'))
438 and: 'there are no more grandchildren as none of the replacement list entries had a child'
439 parentFragment.childFragments.each {assert it.childFragments.size() == 0 }
440 where: 'the following replacement lists are applied'
441 scenario | originalKeys | replacementKeys
442 'one existing entry only' | [] | ['NEW']
443 'multiple new entries' | [] | ['NEW1', 'NEW2']
444 'one new entry only (existing entries are deleted)' | ['A', 'B'] | ['NEW1', 'NEW2']
445 'one existing on new entry' | ['A', 'B'] | ['A', 'NEW']
446 'one existing entry only' | ['A', 'B'] | ['A']
449 @Sql([CLEAR_DATA, SET_DATA])
450 def 'Replacing existing list element with attributes and (grand)child.'() {
451 given: 'a parent with list elements A and B with attribute and grandchild tagged as "org"'
452 def parentXpath = '/parent-3'
453 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'org', ['A','B'], true)
454 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
455 when: 'A is replaced with an entry with attribute and grandchild tagged tagged as "new" (B is not in replacement list)'
456 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new', ['A'], true)
457 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
458 then: 'The updated fragment has a child-list with ONLY element "A"'
459 def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
460 parentFragment.childFragments.size() == 1
461 def childListElementA = parentFragment.childFragments[0]
462 childListElementA.xpath == "/parent-3/child-list[@key='A']"
463 and: 'element "A" has an attribute with the "new" (tag) value'
464 childListElementA.attributes == '{"attr1": "new"}'
465 and: 'element "A" has a only one (grand)child'
466 childListElementA.childFragments.size() == 1
467 and: 'the grandchild is the new grandchild (tag)'
468 def grandChild = childListElementA.childFragments[0]
469 grandChild.xpath == "/parent-3/child-list[@key='A']/new-grand-child"
470 and: 'the grandchild has an attribute with the "new" (tag) value'
471 grandChild.attributes == '{"attr1": "new"}'
474 @Sql([CLEAR_DATA, SET_DATA])
475 def 'Replace list element for a parent (parent-1) with existing one (non-list) child'() {
476 when: 'a list element is added under the parent'
477 def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(XPATH_DATA_NODE_WITH_DESCENDANTS, 'new', ['A','B'], false)
478 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, replacementListEntriesAsDataNodes)
479 then: 'the parent will have 3 children after the replacement'
480 def parentFragment = fragmentRepository.getById(ID_DATA_NODE_WITH_DESCENDANTS)
481 parentFragment.childFragments.size() == 3
482 def xpaths = parentFragment.childFragments.collect {it.xpath}
483 and: 'one of the children is the original child fragment'
484 xpaths.contains('/parent-1/child-1')
485 and: 'it has the two new list elements'
486 xpaths.containsAll("/parent-1/child-list[@key='A']", "/parent-1/child-list[@key='B']")
489 @Sql([CLEAR_DATA, SET_DATA])
490 def 'Replace list content using unknown parent'() {
491 given: 'list element as a collection of data nodes'
492 def listElementCollection = toDataNodes(['irrelevant'])
493 when: 'attempt to replace list elements under unknown parent node'
494 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/unknown', listElementCollection)
495 then: 'a datanode not found exception is thrown'
496 thrown(DataNodeNotFoundException)
499 @Sql([CLEAR_DATA, SET_DATA])
500 def 'Replace list content with empty collection is not supported'() {
501 when: 'attempt to replace list elements with empty collection'
502 objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/parent-203', [])
503 then: 'a CPS admin exception is thrown'
504 def thrown = thrown(CpsAdminException)
505 assert thrown.message == 'Invalid list replacement'
508 @Sql([CLEAR_DATA, SET_DATA])
509 def 'Delete list scenario: #scenario.'() {
510 when: 'deleting list is executed for: #scenario.'
511 objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
512 then: 'only the expected children remain'
513 def parentFragment = fragmentRepository.getById(parentFragmentId)
514 def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
515 assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
516 assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
517 where: 'following parameters were used'
518 scenario | targetXpaths | parentFragmentId || expectedRemainingChildXpaths
519 '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']"]
520 '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']"]
521 'whole list' | '/parent-203/child-204' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203']
522 '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 @Sql([CLEAR_DATA, SET_DATA])
526 def 'Delete list error scenario: #scenario.'() {
527 when: 'attempting to delete scenario: #scenario.'
528 objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
529 then: 'a DataNodeNotFoundException is thrown'
530 thrown(DataNodeNotFoundException)
531 where: 'following parameters were used'
532 scenario | targetXpaths
533 'whole list, parent node does not exist' | '/unknown/some-child'
534 'list element, parent node does not exist' | '/unknown/child-204[@key="A"]'
535 'whole list does not exist' | '/parent-200/unknown'
536 'list element, list does not exist' | '/parent-200/unknown[@key="C"]'
537 'list element, element does not exist' | '/parent-203/child-204[@key="C"]'
538 'valid datanode but not a list' | '/parent-200/child-202'
541 @Sql([CLEAR_DATA, SET_DATA])
542 def 'Confirm deletion of #scenario.'() {
543 given: 'a valid data node'
545 and: 'data nodes are deleted'
546 objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion)
547 when: 'verify data nodes are removed'
548 objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion, INCLUDE_ALL_DESCENDANTS)
550 thrown(DataNodeNotFoundException)
551 and: 'some related object is not deleted'
552 if (xpathSurvivor!=null) {
553 dataNode = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathSurvivor, INCLUDE_ALL_DESCENDANTS)
554 assert dataNode.xpath == xpathSurvivor
556 where: 'following parameters were used'
557 scenario | xpathForDeletion || xpathSurvivor
558 'child data node, parent still exists' | '/parent-206/child-206' || '/parent-206'
559 'list element, sibling still exists' | '/parent-206/child-206/grand-child-206[@key="A"]' || "/parent-206/child-206/grand-child-206[@key='X']"
560 'container node' | '/parent-206' || null
561 'container list node' | '/parent-206[@key="A"]' || "/parent-206[@key='B']"
562 'root node with xpath /' | '/' || null
563 'root node with xpath passed as blank' | '' || null
566 @Sql([CLEAR_DATA, SET_DATA])
567 def 'Delete data node with #scenario.'() {
568 when: 'data node is deleted'
569 objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, datanodeXpath)
570 then: 'a #expectedException is thrown'
571 thrown(expectedException)
572 where: 'the following parameters were used'
573 scenario | datanodeXpath | expectedException
574 'valid data node, non existent child node' | '/parent-203/child-non-existent' | DataNodeNotFoundException
575 'invalid list element' | '/parent-206/child-206/grand-child-206@key="A"]' | PathParsingException
578 @Sql([CLEAR_DATA, SET_DATA])
579 def 'Delete data node for an anchor.'() {
580 given: 'a data-node exists for an anchor'
581 assert fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
582 when: 'data nodes are deleted '
583 objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3)
584 then: 'all data-nodes are deleted successfully'
585 assert !fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
588 def fragmentsExistInDB(dataSpaceId, anchorId) {
589 !fragmentRepository.findRootsByDataspaceAndAnchor(dataSpaceId, anchorId).isEmpty()
592 static Collection<DataNode> toDataNodes(xpaths) {
593 return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
597 static DataNode buildDataNode(xpath, leaves, childDataNodes) {
598 return dataNodeBuilder.withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
601 static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
602 return jsonObjectMapper.convertJsonString(fragmentEntity.attributes, Map<String, Object>.class)
605 def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
606 expectedLeavesMap.forEach((key, value) -> {
607 def actualValue = actualLeavesMap[key]
608 if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
609 assert value.size() == actualValue.size()
610 assert value.containsAll(actualValue)
612 assert value == actualValue
618 def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
619 flatMap.put(dataNodeTree.xpath, dataNodeTree)
620 dataNodeTree.childDataNodes
621 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
625 def keysToXpaths(parent, Collection keys) {
626 return keys.collect { "${parent}/child-list[@key='${it}']".toString() }
629 def static createDataNodeTree(String... xpaths) {
630 def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
631 if (xpaths.length > 1) {
632 def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
633 def childDataNode = createDataNodeTree(xPathsDescendant)
634 dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
636 dataNodeBuilder.build()
639 def getFragmentByXpath(dataspaceName, anchorName, xpath) {
640 def dataspace = dataspaceRepository.getByName(dataspaceName)
641 def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
642 return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
646 def createChildListAllHavingAttributeValue(parentXpath, tag, Collection keys, boolean addGrandChild) {
647 def listElementAsDataNodes = keysToXpaths(parentXpath, keys).collect {
648 new DataNodeBuilder()
650 .withLeaves([attr1: tag])
654 listElementAsDataNodes.each {it.childDataNodes = [createGrandChild(it.xpath, tag)]}
656 return listElementAsDataNodes
659 def createGrandChild(parentXPath, tag) {
660 new DataNodeBuilder()
661 .withXpath("${parentXPath}/${tag}-grand-child")
662 .withLeaves([attr1: tag])