Remove the dependency-cycle between beans
[cps.git] / integration-test / src / test / groovy / org / onap / cps / integration / functional / CpsDataServiceIntegrationSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 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 lists (element) data nodes.'() {
280         given: 'two new (categories) data nodes in two separate batches'
281             def json1 = '{"categories": [ {"code":"new1"} ] }'
282             def json2 = '{"categories": [ {"code":"new2"} ] } '
283         when: 'the batches of new list element(s) are saved'
284             objectUnderTest.saveListElementsBatch(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', [json1, json2], 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 lists (element) data nodes with partial success.'() {
298         given: 'two new (categories) data nodes in two separate batches'
299             def jsonNewElement = '{"categories": [ {"code":"new1"} ] }'
300             def jsonExistingElement = '{"categories": [ {"code":"1"} ] } '
301         when: 'the batches of new list element(s) are saved'
302             objectUnderTest.saveListElementsBatch(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', [jsonNewElement, jsonExistingElement], now)
303         then: 'an already defined (batch) exception is thrown for the existing path'
304             def exceptionThrown = thrown(AlreadyDefinedException)
305             assert exceptionThrown.alreadyDefinedObjectNames ==  ['/bookstore/categories[@code=\'1\']' ] as Set
306         and: 'there is now one extra data node'
307             assert originalCountBookstoreChildNodes + 1 == countDataNodesInBookstore()
308         cleanup:
309             restoreBookstoreDataAnchor(1)
310     }
311
312     def 'Attempt to add empty lists.'() {
313         when: 'the batches of new list element(s) are saved'
314             objectUnderTest.replaceListContent(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', [ ], now)
315         then: 'an admin exception is thrown'
316             thrown(CpsAdminException)
317     }
318
319     def 'Add child error scenario: #scenario.'() {
320         when: 'attempt to add a child data node with #scenario'
321             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, parentXpath, json, now)
322         then: 'a #expectedException is thrown'
323             thrown(expectedException)
324         where: 'the following data is used'
325             scenario                 | parentXpath                              | json                                || expectedException
326             'parent does not exist'  | '/bookstore/categories[@code="unknown"]' | '{"books": [ {"title":"new"} ] } '  || DataNodeNotFoundException
327             'already existing child' | '/bookstore'                             | '{"categories": [ {"code":"1"} ] }' || AlreadyDefinedException
328     }
329
330     def 'Add multiple child data nodes with partial success.'() {
331         given: 'one existing and one new list element'
332             def json = '{"categories": [ {"code":"1"}, {"code":"new"} ] }'
333         when: 'attempt to add the elements'
334             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
335         then: 'an already defined (batch) exception is thrown for the existing path'
336             def thrown  = thrown(AlreadyDefinedException)
337             assert thrown.alreadyDefinedObjectNames == [ "/bookstore/categories[@code='1']" ] as Set
338         and: 'the new data node has been added i.e. can be retrieved'
339             assert objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="new"]', DIRECT_CHILDREN_ONLY).size() == 1
340     }
341
342     def 'Replace list content #scenario.'() {
343         given: 'the bookstore categories 1 and 2 exist and have at least 1 child each '
344             assert countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="1"]', DIRECT_CHILDREN_ONLY)) > 1
345             assert countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="2"]', DIRECT_CHILDREN_ONLY)) > 1
346         when: 'the categories list is replaced with just category "1" and without child nodes (books)'
347             def json = '{"categories": [ {"code":"' +categoryCode + '"' + childJson + '} ] }'
348             objectUnderTest.replaceListContent(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
349         then: 'the new replaced category can be retrieved but has no children anymore'
350             assert expectedNumberOfDataNodes == countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="' +categoryCode + '"]', DIRECT_CHILDREN_ONLY))
351         when: 'attempt to retrieve a category (code) not in the new list'
352             objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/categories[@code="2"]', DIRECT_CHILDREN_ONLY)
353         then: 'a datanode not found exception occurs'
354             thrown(DataNodeNotFoundException)
355         cleanup:
356             restoreBookstoreDataAnchor(1)
357         where: 'the following data is used'
358             scenario                        | categoryCode | childJson                                 || expectedNumberOfDataNodes
359             'existing code, no children'    | '1'          | ''                                        || 1
360             'existing code, new child'      | '1'          | ', "books" : [ { "title": "New Book" } ]' || 2
361             'existing code, existing child' | '1'          | ', "books" : [ { "title": "Matilda" } ]'  || 2
362             'new code, new child'           | 'new'        | ', "books" : [ { "title": "New Book" } ]' || 2
363     }
364
365     def 'Update data node leaves for node that has no leaves (yet).'() {
366         given: 'new (webinfo) datanode without leaves'
367             def json = '{"webinfo": {} }'
368             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
369         when: 'update is performed to add a leaf'
370             def updatedJson = '{"webinfo": {"domain-name":"new leaf data"}}'
371             objectUnderTest.updateNodeLeaves(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, "/bookstore", updatedJson, now)
372         then: 'the updated data nodes are retrieved'
373             def result = cpsDataService.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, "/bookstore/webinfo", INCLUDE_ALL_DESCENDANTS)
374         and: 'the leaf value is updated as expected'
375             assert result.leaves['domain-name'] == ['new leaf data']
376         cleanup:
377             restoreBookstoreDataAnchor(1)
378     }
379
380     def 'Update multiple data leaves error scenario: #scenario.'() {
381         when: 'attempt to update data node for #scenario'
382             objectUnderTest.updateNodeLeaves(dataspaceName, anchorName, xpath, 'irrelevant json data', now)
383         then: 'a #expectedException is thrown'
384             thrown(expectedException)
385         where: 'the following data is used'
386             scenario                 | dataspaceName               | anchorName                 | xpath           || expectedException
387             'invalid dataspace name' | 'Invalid Dataspace'         | 'not-relevant'             | '/not relevant' || DataValidationException
388             'invalid anchor name'    | FUNCTIONAL_TEST_DATASPACE_1 | 'INVALID ANCHOR'           | '/not relevant' || DataValidationException
389             'non-existing dataspace' | 'non-existing-dataspace'    | 'not-relevant'             | '/not relevant' || DataspaceNotFoundException
390             'non-existing anchor'    | FUNCTIONAL_TEST_DATASPACE_1 | 'non-existing-anchor'      | '/not relevant' || AnchorNotFoundException
391             'non-existing-xpath'     | FUNCTIONAL_TEST_DATASPACE_1 | BOOKSTORE_ANCHOR_1         | '/non-existing' || DataValidationException
392     }
393
394     def 'Update data nodes and descendants.'() {
395         given: 'some web info for the bookstore'
396             def json = '{"webinfo": {"domain-name":"ourbookstore.com" ,"contact-email":"info@ourbookstore.com" }}'
397             objectUnderTest.saveData(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1 , '/bookstore', json, now)
398         when: 'the webinfo (container) is updated'
399             json = '{"webinfo": {"domain-name":"newdomain.com" ,"contact-email":"info@newdomain.com" }}'
400             objectUnderTest.updateDataNodeAndDescendants(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', json, now)
401         then: 'webinfo has been updated with teh new details'
402             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore/webinfo', DIRECT_CHILDREN_ONLY)
403             result.leaves.'domain-name'[0] == 'newdomain.com'
404             result.leaves.'contact-email'[0] == 'info@newdomain.com'
405         cleanup:
406             restoreBookstoreDataAnchor(1)
407     }
408
409     def 'Update bookstore top-level container data node.'() {
410         when: 'the bookstore top-level container is updated'
411             def json = '{ "bookstore": { "bookstore-name": "new bookstore" }}'
412             objectUnderTest.updateDataNodeAndDescendants(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/', json, now)
413         then: 'bookstore name has been updated'
414             def result = objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', DIRECT_CHILDREN_ONLY)
415             result.leaves.'bookstore-name'[0] == 'new bookstore'
416         cleanup:
417             restoreBookstoreDataAnchor(1)
418     }
419
420     def 'Update multiple data node leaves.'() {
421         given: 'Updated json for bookstore data'
422             def jsonData =  "{'book-store:books':{'lang':'English/French','price':100,'title':'Matilda'}}"
423         when: 'update is performed for leaves'
424             objectUnderTest.updateNodeLeaves(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_2, "/bookstore/categories[@code='1']", jsonData, now)
425         then: 'the updated data nodes are retrieved'
426             def result = cpsDataService.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_2, "/bookstore/categories[@code=1]/books[@title='Matilda']", INCLUDE_ALL_DESCENDANTS)
427         and: 'the leaf values are updated as expected'
428             assert result.leaves['lang'] == ['English/French']
429             assert result.leaves['price'] == [100]
430         cleanup:
431             restoreBookstoreDataAnchor(2)
432     }
433
434     def 'Get delta between 2 anchors for when #scenario'() {
435         when: 'attempt to get delta report between anchors'
436             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, xpath, fetchDescendantOption)
437         then: 'delta report contains expected number of changes'
438             result.size() == 2
439         and: 'delta report contains expected action'
440             assert result.get(index).getAction() == expectedActions
441         and: 'delta report contains expected xpath'
442             assert result.get(index).getXpath() == expectedXpath
443         where: 'following data was used'
444             scenario            | index | xpath || expectedActions || expectedXpath                                                | fetchDescendantOption
445             'a node is removed' |   0   | '/'   ||    'remove'     || "/bookstore-address[@bookstore-name='Easons-1']"             | OMIT_DESCENDANTS
446             'a node is added'   |   1   | '/'   ||     'add'       || "/bookstore-address[@bookstore-name='Crossword Bookstores']" | OMIT_DESCENDANTS
447     }
448
449     def 'Get delta between 2 anchors where child nodes are added/removed but parent node remains unchanged'() {
450         def parentNodeXpath = "/bookstore"
451         when: 'attempt to get delta report between anchors'
452             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
453         then: 'delta report contains expected number of changes'
454             result.size() == 11
455         and: 'the delta report does not contain parent node xpath'
456             def xpaths = getDeltaReportEntities(result).get('xpaths')
457             assert !(xpaths.contains(parentNodeXpath))
458     }
459
460     def 'Get delta between 2 anchors returns empty response when #scenario'() {
461         when: 'attempt to get delta report between anchors'
462             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, sourceAnchor, targetAnchor, xpath, INCLUDE_ALL_DESCENDANTS)
463         then: 'delta report is empty'
464             assert result.isEmpty()
465         where: 'following data was used'
466             scenario                              | sourceAnchor       | targetAnchor       | xpath
467         'anchors with identical data are queried' | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_4 | '/'
468         'same anchor name is passed as parameter' | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_3 | '/'
469         'non existing xpath'                      | BOOKSTORE_ANCHOR_3 | BOOKSTORE_ANCHOR_5 | '/non-existing-xpath'
470     }
471
472     def 'Get delta between anchors error scenario: #scenario'() {
473         when: 'attempt to get delta between anchors'
474             objectUnderTest.getDeltaByDataspaceAndAnchors(dataspaceName, sourceAnchor, targetAnchor, '/some-xpath', INCLUDE_ALL_DESCENDANTS)
475         then: 'expected exception is thrown'
476             thrown(expectedException)
477         where: 'following data was used'
478                     scenario                               | dataspaceName               | sourceAnchor          | targetAnchor          || expectedException
479             'invalid dataspace name'                       | 'Invalid dataspace'         | 'not-relevant'        | 'not-relevant'        || DataValidationException
480             'invalid anchor 1 name'                        | FUNCTIONAL_TEST_DATASPACE_3 | 'invalid anchor'      | 'not-relevant'        || DataValidationException
481             'invalid anchor 2 name'                        | FUNCTIONAL_TEST_DATASPACE_3 | BOOKSTORE_ANCHOR_3    | 'invalid anchor'      || DataValidationException
482             'non-existing dataspace'                       | 'non-existing'              | 'not-relevant1'       | 'not-relevant2'       || DataspaceNotFoundException
483             'non-existing dataspace with same anchor name' | 'non-existing'              | 'not-relevant'        | 'not-relevant'        || DataspaceNotFoundException
484             'non-existing anchor 1'                        | FUNCTIONAL_TEST_DATASPACE_3 | 'non-existing-anchor' | 'not-relevant'        || AnchorNotFoundException
485             'non-existing anchor 2'                        | FUNCTIONAL_TEST_DATASPACE_3 | BOOKSTORE_ANCHOR_3    | 'non-existing-anchor' || AnchorNotFoundException
486     }
487
488     def 'Get delta between anchors for remove action, where source data node #scenario'() {
489         when: 'attempt to get delta between leaves of data nodes present in 2 anchors'
490             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_5, BOOKSTORE_ANCHOR_3, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
491         then: 'expected action is present in delta report'
492             assert result.get(0).getAction() == 'remove'
493         where: 'following data was used'
494             scenario                     | parentNodeXpath
495             'has leaves and child nodes' | "/bookstore/categories[@code='6']"
496             'has leaves only'            | "/bookstore/categories[@code='5']/books[@title='Book 11']"
497             'has child data node only'   | "/bookstore/support-info/contact-emails"
498             'is empty'                   | "/bookstore/container-without-leaves"
499     }
500
501     def 'Get delta between anchors for add action, where target data node #scenario'() {
502         when: 'attempt to get delta between leaves of data nodes present in 2 anchors'
503             def result = objectUnderTest.getDeltaByDataspaceAndAnchors(FUNCTIONAL_TEST_DATASPACE_3, BOOKSTORE_ANCHOR_3, BOOKSTORE_ANCHOR_5, parentNodeXpath, INCLUDE_ALL_DESCENDANTS)
504         then: 'the expected action is present in delta report'
505             result.get(0).getAction() == 'add'
506         and: 'the expected xapth is present in delta report'
507             result.get(0).getXpath() == parentNodeXpath
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 getDeltaReportEntities(List<DeltaReport> deltaReport) {
517         def xpaths = []
518         def action = []
519         def sourcePayload = []
520         def targetPayload = []
521         deltaReport.each {
522             delta -> xpaths.add(delta.getXpath())
523                 action.add(delta.getAction())
524                 sourcePayload.add(delta.getSourceData())
525                 targetPayload.add(delta.getTargetData())
526         }
527         return ['xpaths':xpaths, 'action':action, 'sourcePayload':sourcePayload, 'targetPayload':targetPayload]
528     }
529
530     def countDataNodesInBookstore() {
531         return countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/bookstore', INCLUDE_ALL_DESCENDANTS))
532     }
533
534     def countTopLevelListDataNodesInBookstore() {
535         return countDataNodesInTree(objectUnderTest.getDataNodes(FUNCTIONAL_TEST_DATASPACE_1, BOOKSTORE_ANCHOR_1, '/', INCLUDE_ALL_DESCENDANTS))
536     }
537 }