CmHandle delete is failing with InternalServerError: Null key is not allowed - add...
[cps.git] / integration-test / src / test / groovy / org / onap / cps / integration / functional / CpsDataServiceIntegrationSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2023 TechMahindra Ltd.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the 'License');
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an 'AS IS' BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.integration.functional
23
24 import org.onap.cps.api.CpsDataService
25 import org.onap.cps.integration.base.FunctionalSpecBase
26 import org.onap.cps.spi.FetchDescendantsOption
27 import org.onap.cps.spi.exceptions.AlreadyDefinedException
28 import org.onap.cps.spi.exceptions.AnchorNotFoundException
29 import org.onap.cps.spi.exceptions.CpsAdminException
30 import org.onap.cps.spi.exceptions.CpsPathException
31 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
32 import org.onap.cps.spi.exceptions.DataNodeNotFoundExceptionBatch
33 import org.onap.cps.spi.exceptions.DataValidationException
34 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
35 import org.onap.cps.spi.model.DeltaReport
36
37 import static org.onap.cps.spi.FetchDescendantsOption.DIRECT_CHILDREN_ONLY
38 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
39 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
40
41 class CpsDataServiceIntegrationSpec extends FunctionalSpecBase {
42
43     CpsDataService objectUnderTest
44     def originalCountBookstoreChildNodes
45     def originalCountBookstoreTopLevelListNodes
46
47     def setup() {
48         objectUnderTest = cpsDataService
49         originalCountBookstoreChildNodes = countDataNodesInBookstore()
50         originalCountBookstoreTopLevelListNodes = countTopLevelListDataNodesInBookstore()
51     }
52
53     def 'Read bookstore top-level container(s) using #fetchDescendantsOption.'() {
54         when: 'get data nodes for bookstore container'
55             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', fetchDescendantsOption)
56         then: 'the tree consist ouf of #expectNumberOfDataNodes data nodes'
57             assert countDataNodesInTree(result) == expectNumberOfDataNodes
58         and: 'the top level data node has the expected attribute and value'
59             assert result.leaves['bookstore-name'] == ['Easons-1']
60         and: 'they are from the correct dataspace'
61             assert result.dataspace == [FUNCTIONAL_TEST_DATASPACE_1]
62         and: 'they are from the correct anchor'
63             assert result.anchorName == [BOOKSTORE_ANCHOR_1]
64         where: 'the following option is used'
65             fetchDescendantsOption        || expectNumberOfDataNodes
66             OMIT_DESCENDANTS              || 1
67             DIRECT_CHILDREN_ONLY          || 7
68             INCLUDE_ALL_DESCENDANTS       || 28
69             new FetchDescendantsOption(2) || 28
70     }
71
72     def 'Read bookstore top-level container(s) using "root" path variations.'() {
73         when: 'get data nodes for bookstore container'
74             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, root, OMIT_DESCENDANTS)
75         then: 'the tree consist correct number of data nodes'
76             assert countDataNodesInTree(result) == 2
77         and: 'the top level data node has the expected number of leaves'
78             assert result.leaves.size() == 2
79         where: 'the following variations of "root" are used'
80             root << [ '/', '' ]
81     }
82
83     def 'Read data nodes with error: #cpsPath'() {
84         when: 'attempt to get data nodes using invalid path'
85             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, cpsPath, DIRECT_CHILDREN_ONLY)
86         then: 'a #expectedException is thrown'
87             thrown(expectedException)
88         where:
89             cpsPath              || expectedException
90             'invalid path'       || CpsPathException
91             '/non-existing-path' || DataNodeNotFoundException
92     }
93
94     def 'Read (multiple) data nodes (batch) with #cpsPath'() {
95         when: 'attempt to get data nodes using invalid path'
96             objectUnderTest.getDataNodesForMultipleXpaths(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, [ cpsPath ], DIRECT_CHILDREN_ONLY)
97         then: 'no exception is thrown'
98             noExceptionThrown()
99         where:
100             cpsPath << [ 'invalid path', '/non-existing-path' ]
101     }
102
103     def 'Get data nodes error scenario #scenario'() {
104         when: 'attempt to retrieve data nodes'
105             objectUnderTest.getDataNodes(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
106         then: 'expected exception is thrown'
107             thrown(expectedException)
108         where: 'following data is used'
109             scenario                 | dataspaceName                | anchorName        | xpath           || expectedException
110             'non existent dataspace' | 'non-existent'               | 'not-relevant'    | '/not-relevant' || DataspaceNotFoundException
111             'non existent anchor'    | FUNCTIONAL_TEST_DATASPACE_1  | 'non-existent'    | '/not-relevant' || AnchorNotFoundException
112             'non-existent xpath'     | FUNCTIONAL_TEST_DATASPACE_1  | BOOKSTORE_ANCHOR_1| '/non-existing' || DataNodeNotFoundException
113             'invalid-dataspace'      | 'Invalid dataspace'          | 'not-relevant'    | '/not-relevant' || DataValidationException
114             'invalid-dataspace'      | FUNCTIONAL_TEST_DATASPACE_1  | 'Invalid Anchor'  | '/not-relevant' || DataValidationException
115     }
116
117     def 'Delete root data node.'() {
118         when: 'the "root" is deleted'
119             objectUnderTest.deleteDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, [ '/' ], now)
120         and: 'attempt to get the top level data node'
121             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', DIRECT_CHILDREN_ONLY)
122         then: 'an datanode not found exception is thrown'
123             thrown(DataNodeNotFoundException)
124         cleanup:
125             restoreBookstoreDataAnchor(1)
126     }
127
128     def 'Get whole list data' () {
129             def xpathForWholeList = "/bookstore/categories"
130         when: 'get data nodes for bookstore container'
131             def dataNodes = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, xpathForWholeList, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
132         then: 'the tree consist ouf of #expectNumberOfDataNodes data nodes'
133             assert dataNodes.size() == 5
134         and: 'each datanode contains the list node xpath partially in its xpath'
135             dataNodes.each {dataNode ->
136                 assert dataNode.xpath.contains(xpathForWholeList)
137             }
138     }
139
140     def 'Read (multiple) data nodes with #scenario' () {
141         when: 'attempt to get data nodes using multiple valid xpaths'
142             def dataNodes = objectUnderTest.getDataNodesForMultipleXpaths(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, xpath, OMIT_DESCENDANTS)
143         then: 'expected numer of data nodes are returned'
144             dataNodes.size() == expectedNumberOfDataNodes
145         where: 'the following data was used'
146                     scenario                    |                       xpath                                       |   expectedNumberOfDataNodes
147             'container-node xpath'              | ['/bookstore']                                                    |               1
148             'list-item'                         | ['/bookstore/categories[@code=1]']                                |               1
149             'parent-list xpath'                 | ['/bookstore/categories']                                         |               5
150             'child-list xpath'                  | ['/bookstore/categories[@code=1]/books']                          |               2
151             'both parent and child list xpath'  | ['/bookstore/categories', '/bookstore/categories[@code=1]/books'] |               7
152     }
153
154     def 'Add and Delete a (container) data node using #scenario.'() {
155             when: 'the new datanode is saved'
156                 objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , parentXpath, json, now)
157             then: 'it can be retrieved by its normalized xpath'
158                 def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, normalizedXpathToNode, DIRECT_CHILDREN_ONLY)
159                 assert result.size() == 1
160                 assert result[0].xpath == normalizedXpathToNode
161             and: 'there is now one extra datanode'
162                 assert originalCountBookstoreChildNodes + 1 == countDataNodesInBookstore()
163             when: 'the new datanode is deleted'
164                 objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, normalizedXpathToNode, now)
165             then: 'the original number of data nodes is restored'
166                 assert originalCountBookstoreChildNodes == countDataNodesInBookstore()
167             where:
168                 scenario                      | parentXpath                         | json                                                                                        || normalizedXpathToNode
169                 'normalized parent xpath'     | '/bookstore'                        | '{"webinfo": {"domain-name":"ourbookstore.com", "contact-email":"info@ourbookstore.com" }}' || "/bookstore/webinfo"
170                 'non-normalized parent xpath' | '/bookstore/categories[ @code="1"]' | '{"books": {"title":"new" }}'                                                               || "/bookstore/categories[@code='1']/books[@title='new']"
171     }
172
173     def 'Attempt to create a top level data node using root.'() {
174         given: 'a new anchor'
175             cpsAnchorService.createAnchor(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_SCHEMA_SET, 'newAnchor1');
176         when: 'attempt to save new top level datanode'
177             def json = '{"bookstore": {"bookstore-name": "New Store"} }'
178             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, 'newAnchor1' , '/', json, now)
179         then: 'since there is no data a data node not found exception is thrown'
180             thrown(DataNodeNotFoundException)
181     }
182
183     def 'Attempt to save top level data node that already exist'() {
184         when: 'attempt to save already existing top level node'
185             def json = '{"bookstore": {} }'
186             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, json, now)
187         then: 'an exception that (one cps paths is)  already defined is thrown '
188             def exceptionThrown = thrown(AlreadyDefinedException)
189             exceptionThrown.alreadyDefinedObjectNames == ['/bookstore' ] as Set
190         cleanup:
191             restoreBookstoreDataAnchor(1)
192     }
193
194     def 'Delete a single datanode with invalid path.'() {
195         when: 'attempt to delete a single datanode with invalid path'
196             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/invalid path', now)
197         then: 'a cps path parser exception is thrown'
198             thrown(CpsPathException)
199     }
200
201     def 'Delete multiple data nodes with invalid path.'() {
202         when: 'attempt to delete datanode collection with invalid path'
203             objectUnderTest.deleteDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, ['/invalid path'], now)
204         then: 'the error is silently ignored'
205             noExceptionThrown()
206     }
207
208     def 'Delete single data node with non-existing path.'() {
209         when: 'attempt to delete a single datanode non-existing invalid path'
210             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/does/not/exist', now)
211         then: 'a datanode not found exception is thrown'
212             thrown(DataNodeNotFoundException)
213     }
214
215     def 'Delete multiple data nodes with non-existing path(s).'() {
216         when: 'attempt to delete a single datanode non-existing invalid path'
217             objectUnderTest.deleteDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, ['/does/not/exist'], now)
218         then: 'a  datanode not found (batch) exception is thrown'
219             thrown(DataNodeNotFoundExceptionBatch)
220     }
221
222     def 'Add and Delete top-level list (element) data nodes with root node.'() {
223         given: 'a new (multiple-data-tree:invoice) datanodes'
224             def json = '{"bookstore-address":[{"bookstore-name":"Easons","address":"Bangalore,India","postal-code":"560043"}]}'
225         when: 'the new list elements are saved'
226             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/', json, now)
227         then: 'they can be retrieved by their xpaths'
228             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore-address[@bookstore-name="Easons"]', INCLUDE_ALL_DESCENDANTS)
229         and: 'there is one extra datanode'
230             assert originalCountBookstoreTopLevelListNodes + 1 == countTopLevelListDataNodesInBookstore()
231         when: 'the new elements are deleted'
232             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore-address[@bookstore-name="Easons"]', now)
233         then: 'the original number of datanodes is restored'
234             assert originalCountBookstoreTopLevelListNodes == countTopLevelListDataNodesInBookstore()
235     }
236
237     def 'Add and Delete list (element) data nodes.'() {
238         given: 'two new (categories) data nodes'
239             def json = '{"categories": [ {"code":"new1"}, {"code":"new2" } ] }'
240         when: 'the new list elements are saved'
241             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
242         then: 'they can be retrieved by their xpaths'
243             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new1"]', DIRECT_CHILDREN_ONLY).size() == 1
244             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new2"]', DIRECT_CHILDREN_ONLY).size() == 1
245         and: 'there are now two extra data nodes'
246             assert originalCountBookstoreChildNodes + 2 == countDataNodesInBookstore()
247         when: 'the new elements are deleted'
248             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new1"]', now)
249             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new2"]', now)
250         then: 'the original number of data nodes is restored'
251             assert originalCountBookstoreChildNodes == countDataNodesInBookstore()
252     }
253
254     def 'Add list (element) data nodes that already exist.'() {
255         given: 'two (categories) data nodes, one new and one existing'
256             def json = '{"categories": [ {"code":"1"}, {"code":"new1"} ] }'
257         when: 'attempt to save the list element'
258             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
259         then: 'an exception that (one cps paths is)  already defined is thrown '
260             def exceptionThrown = thrown(AlreadyDefinedException)
261             exceptionThrown.alreadyDefinedObjectNames == ['/bookstore/categories[@code=\'1\']' ] as Set
262         and: 'there is now one extra data nodes'
263             assert originalCountBookstoreChildNodes + 1 == countDataNodesInBookstore()
264         cleanup:
265             restoreBookstoreDataAnchor(1)
266     }
267
268     def 'Add and Delete list (element) data nodes using lists specific method.'() {
269         given: 'a new (categories) data nodes'
270             def json = '{"categories": [ {"code":"new1"} ] }'
271         and: 'the new list element is saved'
272             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
273         when: 'the new element is deleted'
274             objectUnderTest.deleteListOrListElement(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new1"]', now)
275         then: 'the original number of data nodes is restored'
276             assert originalCountBookstoreChildNodes == countDataNodesInBookstore()
277     }
278
279     def 'Add and Delete a batch of list element data nodes.'() {
280         given: 'two new (categories) data nodes in a single batch'
281             def json = '{"categories": [ {"code":"new1"}, {"code":"new2"} ] }'
282         when: 'the batches of new list element(s) are saved'
283             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
284         then: 'they can be retrieved by their xpaths'
285             assert objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new1"]', DIRECT_CHILDREN_ONLY).size() == 1
286             assert objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new2"]', DIRECT_CHILDREN_ONLY).size() == 1
287         and: 'there are now two extra data nodes'
288             assert originalCountBookstoreChildNodes + 2 == countDataNodesInBookstore()
289         when: 'the new elements are deleted'
290             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new1"]', now)
291             objectUnderTest.deleteDataNode(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new2"]', now)
292         then: 'the original number of data nodes is restored'
293             assert originalCountBookstoreChildNodes == countDataNodesInBookstore()
294     }
295
296     def 'Add and Delete a batch of list element data nodes with partial success.'() {
297         given: 'one existing and one new (categories) data nodes in a single batch'
298             def json = '{"categories": [ {"code":"new1"}, {"code":"1"} ] }'
299         when: 'the batches of new list element(s) are saved'
300             objectUnderTest.saveListElements(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
301         then: 'an already defined (batch) exception is thrown for the existing path'
302             def exceptionThrown = thrown(AlreadyDefinedException)
303             assert exceptionThrown.alreadyDefinedObjectNames ==  ['/bookstore/categories[@code=\'1\']' ] as Set
304         and: 'there is now one extra data node'
305             assert originalCountBookstoreChildNodes + 1 == countDataNodesInBookstore()
306         cleanup:
307             restoreBookstoreDataAnchor(1)
308     }
309
310     def 'Attempt to add empty lists.'() {
311         when: 'the batches of new list element(s) are saved'
312             objectUnderTest.replaceListContent(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', [ ], now)
313         then: 'an admin exception is thrown'
314             thrown(CpsAdminException)
315     }
316
317     def 'Add child error scenario: #scenario.'() {
318         when: 'attempt to add a child data node with #scenario'
319             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, parentXpath, json, now)
320         then: 'a #expectedException is thrown'
321             thrown(expectedException)
322         where: 'the following data is used'
323             scenario                 | parentXpath                              | json                                || expectedException
324             'parent does not exist'  | '/bookstore/categories[@code="unknown"]' | '{"books": [ {"title":"new"} ] } '  || DataNodeNotFoundException
325             'already existing child' | '/bookstore'                             | '{"categories": [ {"code":"1"} ] }' || AlreadyDefinedException
326     }
327
328     def 'Add multiple child data nodes with partial success.'() {
329         given: 'one existing and one new list element'
330             def json = '{"categories": [ {"code":"1"}, {"code":"new"} ] }'
331         when: 'attempt to add the elements'
332             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
333         then: 'an already defined (batch) exception is thrown for the existing path'
334             def thrown  = thrown(AlreadyDefinedException)
335             assert thrown.alreadyDefinedObjectNames == [ "/bookstore/categories[@code='1']" ] as Set
336         and: 'the new data node has been added i.e. can be retrieved'
337             assert objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new"]', DIRECT_CHILDREN_ONLY).size() == 1
338     }
339
340     def 'Replace list content #scenario.'() {
341         given: 'the bookstore categories 1 and 2 exist and have at least 1 child each '
342             assert countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="1"]', DIRECT_CHILDREN_ONLY)) > 1
343             assert countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="2"]', DIRECT_CHILDREN_ONLY)) > 1
344         when: 'the categories list is replaced with just category "1" and without child nodes (books)'
345             def json = '{"categories": [ {"code":"' +categoryCode + '"' + childJson + '} ] }'
346             objectUnderTest.replaceListContent(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
347         then: 'the new replaced category can be retrieved but has no children anymore'
348             assert expectedNumberOfDataNodes == countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="' +categoryCode + '"]', DIRECT_CHILDREN_ONLY))
349         when: 'attempt to retrieve a category (code) not in the new list'
350             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="2"]', DIRECT_CHILDREN_ONLY)
351         then: 'a datanode not found exception occurs'
352             thrown(DataNodeNotFoundException)
353         cleanup:
354             restoreBookstoreDataAnchor(1)
355         where: 'the following data is used'
356             scenario                        | categoryCode | childJson                                 || expectedNumberOfDataNodes
357             'existing code, no children'    | '1'          | ''                                        || 1
358             'existing code, new child'      | '1'          | ', "books" : [ { "title": "New Book" } ]' || 2
359             'existing code, existing child' | '1'          | ', "books" : [ { "title": "Matilda" } ]'  || 2
360             'new code, new child'           | 'new'        | ', "books" : [ { "title": "New Book" } ]' || 2
361     }
362
363     def 'Update data node leaves for node that has no leaves (yet).'() {
364         given: 'new (webinfo) datanode without leaves'
365             def json = '{"webinfo": {} }'
366             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
367         when: 'update is performed to add a leaf'
368             def updatedJson = '{"webinfo": {"domain-name":"new leaf data"}}'
369             objectUnderTest.updateNodeLeaves(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, "/bookstore", updatedJson, now)
370         then: 'the updated data nodes are retrieved'
371             def result = cpsDataService.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, "/bookstore/webinfo", INCLUDE_ALL_DESCENDANTS)
372         and: 'the leaf value is updated as expected'
373             assert result.leaves['domain-name'] == ['new leaf data']
374         cleanup:
375             restoreBookstoreDataAnchor(1)
376     }
377
378     def 'Update multiple data leaves error scenario: #scenario.'() {
379         when: 'attempt to update data node for #scenario'
380             objectUnderTest.updateNodeLeaves(dataspaceName, anchorName, xpath, 'irrelevant json data', now)
381         then: 'a #expectedException is thrown'
382             thrown(expectedException)
383         where: 'the following data is used'
384             scenario                 | dataspaceName               | anchorName                 | xpath           || expectedException
385             'invalid dataspace name' | 'Invalid Dataspace'         | 'not-relevant'             | '/not relevant' || DataValidationException
386             'invalid anchor name'    | FUNCTIONAL_TEST_DATASPACE_1 | 'INVALID ANCHOR'           | '/not relevant' || DataValidationException
387             'non-existing dataspace' | 'non-existing-dataspace'    | 'not-relevant'             | '/not relevant' || DataspaceNotFoundException
388             'non-existing anchor'    | FUNCTIONAL_TEST_DATASPACE_1 | 'non-existing-anchor'      | '/not relevant' || AnchorNotFoundException
389             'non-existing-xpath'     | FUNCTIONAL_TEST_DATASPACE_1 | BOOKSTORE_ANCHOR_1         | '/non-existing' || DataValidationException
390     }
391
392     def 'Update data nodes and descendants.'() {
393         given: 'some web info for the bookstore'
394             def json = '{"webinfo": {"domain-name":"ourbookstore.com" ,"contact-email":"info@ourbookstore.com" }}'
395             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
396         when: 'the webinfo (container) is updated'
397             json = '{"webinfo": {"domain-name":"newdomain.com" ,"contact-email":"info@newdomain.com" }}'
398             objectUnderTest.updateDataNodeAndDescendants(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
399         then: 'webinfo has been updated with teh new details'
400             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/webinfo', DIRECT_CHILDREN_ONLY)
401             result.leaves.'domain-name'[0] == 'newdomain.com'
402             result.leaves.'contact-email'[0] == 'info@newdomain.com'
403         cleanup:
404             restoreBookstoreDataAnchor(1)
405     }
406
407     def 'Update bookstore top-level container data node.'() {
408         when: 'the bookstore top-level container is updated'
409             def json = '{ "bookstore": { "bookstore-name": "new bookstore" }}'
410             objectUnderTest.updateDataNodeAndDescendants(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/', json, now)
411         then: 'bookstore name has been updated'
412             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', DIRECT_CHILDREN_ONLY)
413             result.leaves.'bookstore-name'[0] == 'new bookstore'
414         cleanup:
415             restoreBookstoreDataAnchor(1)
416     }
417
418     def 'Update multiple data node leaves.'() {
419         given: 'Updated json for bookstore data'
420             def jsonData =  "{'book-store:books':{'lang':'English/French','price':100,'title':'Matilda'}}"
421         when: 'update is performed for leaves'
422             objectUnderTest.updateNodeLeaves(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_2, "/bookstore/categories[@code='1']", jsonData, now)
423         then: 'the updated data nodes are retrieved'
424             def result = cpsDataService.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_2, "/bookstore/categories[@code=1]/books[@title='Matilda']", INCLUDE_ALL_DESCENDANTS)
425         and: 'the leaf values are updated as expected'
426             assert result.leaves['lang'] == ['English/French']
427             assert result.leaves['price'] == [100]
428         cleanup:
429             restoreBookstoreDataAnchor(2)
430     }
431
432     def 'Get delta between 2 anchors for when #scenario'() {
433         when: 'attempt to get delta report between anchors'
434             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, '/', OMIT_DESCENDANTS)
435         then: 'delta report contains expected number of changes'
436             result.size() == 3
437         and: 'delta report contains UPDATE action with expected xpath'
438             assert result[0].getAction() == 'update'
439             assert result[0].getXpath() == '/bookstore'
440         and: 'delta report contains REMOVE action with expected xpath'
441             assert result[1].getAction() == 'remove'
442             assert result[1].getXpath() == "/bookstore-address[@bookstore-name='Easons-1']"
443         and: 'delta report contains ADD action with expected xpath'
444             assert result[2].getAction() == 'add'
445             assert result[2].getXpath() == "/bookstore-address[@bookstore-name='Crossword Bookstores']"
446     }
447
448     def 'Get delta between 2 anchors returns empty response when #scenario'() {
449         when: 'attempt to get delta report between anchors'
450             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, targetAnchor, xpath, INCLUDE_ALL_DESCENDANTS)
451         then: 'delta report is empty'
452             assert result.isEmpty()
453         where: 'following data was used'
454             scenario                              | targetAnchor       | xpath
455         'anchors with identical data are queried' | BOOKSTORE_ANCHOR_4 | '/'
456         'same anchor name is passed as parameter' | BOOKSTORE_ANCHOR_3 | '/'
457         'non existing xpath'                      | BOOKSTORE_ANCHOR_5 | '/non-existing-xpath'
458     }
459
460     def 'Get delta between anchors error scenario: #scenario'() {
461         when: 'attempt to get delta between anchors'
462             objectUnderTest.getDeltaByDataspaceAndAnchors(dataspaceName, sourceAnchor, targetAnchor, '/some-xpath', INCLUDE_ALL_DESCENDANTS)
463         then: 'expected exception is thrown'
464             thrown(expectedException)
465         where: 'following data was used'
466                     scenario                               | dataspaceName               | sourceAnchor          | targetAnchor          || expectedException
467             'invalid dataspace name'                       | 'Invalid dataspace'         | 'not-relevant'        | 'not-relevant'        || DataValidationException
468             'invalid anchor 1 name'                        | FUNCTIONAL_TEST_DATASPACE_3 | 'invalid anchor'      | 'not-relevant'        || DataValidationException
469             'invalid anchor 2 name'                        | FUNCTIONAL_TEST_DATASPACE_3 | BOOKSTORE_ANCHOR_3    | 'invalid anchor'      || DataValidationException
470             'non-existing dataspace'                       | 'non-existing'              | 'not-relevant1'       | 'not-relevant2'       || DataspaceNotFoundException
471             'non-existing dataspace with same anchor name' | 'non-existing'              | 'not-relevant'        | 'not-relevant'        || DataspaceNotFoundException
472             'non-existing anchor 1'                        | FUNCTIONAL_TEST_DATASPACE_3 | 'non-existing-anchor' | 'not-relevant'        || AnchorNotFoundException
473             'non-existing anchor 2'                        | FUNCTIONAL_TEST_DATASPACE_3 | BOOKSTORE_ANCHOR_3    | 'non-existing-anchor' || AnchorNotFoundException
474     }
475
476     def 'Get delta between anchors for remove action, where source data node #scenario'() {
477         when: 'attempt to get delta between leaves of data nodes present in 2 anchors'
478             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_5, BOOKSTORE_ANCHOR_3, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
479         then: 'expected action is present in delta report'
480             assert result.get(0).getAction() == 'remove'
481         where: 'following data was used'
482             scenario                     | parentNodeXpath
483             'has leaves and child nodes' | "/bookstore/categories[@code='6']"
484             'has leaves only'            | "/bookstore/categories[@code='5']/books[@title='Book 11']"
485             'has child data node only'   | "/bookstore/support-info/contact-emails"
486             'is empty'                   | "/bookstore/container-without-leaves"
487     }
488
489     def 'Get delta between anchors for add action, where target data node #scenario'() {
490         when: 'attempt to get delta between leaves of data nodes present in 2 anchors'
491             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
492         then: 'the expected action is present in delta report'
493             result.get(0).getAction() == 'add'
494         and: 'the expected xapth is present in delta report'
495             result.get(0).getXpath() == parentNodeXpath
496         where: 'following data was used'
497             scenario                     | parentNodeXpath
498             'has leaves and child nodes' | "/bookstore/categories[@code='6']"
499             'has leaves only'            | "/bookstore/categories[@code='5']/books[@title='Book 11']"
500             'has child data node only'   | "/bookstore/support-info/contact-emails"
501             'is empty'                   | "/bookstore/container-without-leaves"
502     }
503
504     def 'Get delta between anchors when leaves of existing data nodes are updated,: #scenario'() {
505         when: 'attempt to get delta between leaves of existing data nodes'
506             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, sourceAnchor, targetAnchor, xpath, OMIT_DESCENDANTS)
507         then: 'expected action is update'
508             assert result[0].getAction() == 'update'
509         and: 'the payload has expected leaf values'
510             def sourceData = result[0].getSourceData()
511             def targetData = result[0].getTargetData()
512             assert sourceData == expectedSourceValue
513             assert targetData == expectedTargetValue
514         where: 'following data was used'
515             scenario                           | sourceAnchor       | targetAnchor       | xpath                                                     || expectedSourceValue            | expectedTargetValue
516             'leaf is updated in target anchor' | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_5 | '/bookstore'                                              || ['bookstore-name': 'Easons-1'] | ['bookstore-name': 'Crossword Bookstores']
517             'leaf is removed in target anchor' | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_5 | "/bookstore/categories[@code='5']/books[@title='Book 1']" || [price:1]                      | null
518             'leaf is added in target anchor'   | BOOKSTORE_ANCHOR_5 | BOOKSTORE_ANCHOR_3 | "/bookstore/categories[@code='5']/books[@title='Book 1']" || null                           | [price:1]
519     }
520
521     def 'Get delta between anchors when child data nodes under existing parent data nodes are updated: #scenario'() {
522         when: 'attempt to get delta between leaves of existing data nodes'
523             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, sourceAnchor, targetAnchor, xpath, DIRECT_CHILDREN_ONLY)
524         then: 'expected action is update'
525             assert result[0].getAction() == 'update'
526         and: 'the delta report has expected child node xpaths'
527             def deltaReportEntities = getDeltaReportEntities(result)
528             def childNodeXpathsInDeltaReport = deltaReportEntities.get('xpaths')
529             assert childNodeXpathsInDeltaReport.contains(expectedChildNodeXpath)
530         where: 'following data was used'
531             scenario                                          | sourceAnchor       | targetAnchor       | xpath                 || expectedChildNodeXpath
532             'source and target anchors have child data nodes' | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_5 | '/bookstore/premises' || '/bookstore/premises/addresses[@house-number=\'2\' and @street=\'Main Street\']'
533             'removed child data nodes in target anchor'       | BOOKSTORE_ANCHOR_5 | BOOKSTORE_ANCHOR_3 | '/bookstore'          || '/bookstore/support-info'
534             'added  child data nodes in target anchor'        | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_5 | '/bookstore'          || '/bookstore/support-info'
535     }
536
537     def 'Get delta between anchors where source and target data nodes have leaves and child data nodes'() {
538         given: 'parent node xpath and expected data in delta report'
539             def parentNodeXpath = "/bookstore/categories[@code='1']"
540             def expectedSourceDataInParentNode = ['name':'Children']
541             def expectedTargetDataInParentNode = ['name':'Kids']
542             def expectedSourceDataInChildNode = [['lang' : 'English'],['price':20, 'editions':[1988, 2000]]]
543             def expectedTargetDataInChildNode = [['lang':'English/German'], ['price':200, 'editions':[2023, 1988, 2000]]]
544         when: 'attempt to get delta between leaves of existing data nodes'
545             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
546             def deltaReportEntities = getDeltaReportEntities(result)
547         then: 'expected action is update'
548             assert result[0].getAction() == 'update'
549         and: 'the payload has expected parent node xpath'
550             assert deltaReportEntities.get('xpaths').contains(parentNodeXpath)
551         and: 'delta report has expected source and target data'
552             assert deltaReportEntities.get('sourcePayload').contains(expectedSourceDataInParentNode)
553             assert deltaReportEntities.get('targetPayload').contains(expectedTargetDataInParentNode)
554         and: 'the delta report also has expected child node xpaths'
555             assert deltaReportEntities.get('xpaths').containsAll(["/bookstore/categories[@code='1']/books[@title='The Gruffalo']", "/bookstore/categories[@code='1']/books[@title='Matilda']"])
556         and: 'the delta report also has expected source and target data of child nodes'
557             assert deltaReportEntities.get('sourcePayload').containsAll(expectedSourceDataInChildNode)
558             assert deltaReportEntities.get('targetPayload').containsAll(expectedTargetDataInChildNode)
559
560     }
561
562     def getDeltaReportEntities(List<DeltaReport> deltaReport) {
563         def xpaths = []
564         def action = []
565         def sourcePayload = []
566         def targetPayload = []
567         deltaReport.each {
568             delta -> xpaths.add(delta.getXpath())
569                 action.add(delta.getAction())
570                 sourcePayload.add(delta.getSourceData())
571                 targetPayload.add(delta.getTargetData())
572         }
573         return ['xpaths':xpaths, 'action':action, 'sourcePayload':sourcePayload, 'targetPayload':targetPayload]
574     }
575
576     def countDataNodesInBookstore() {
577         return countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', INCLUDE_ALL_DESCENDANTS))
578     }
579
580     def countTopLevelListDataNodesInBookstore() {
581         return countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/', INCLUDE_ALL_DESCENDANTS))
582     }
583 }