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