Editing of Nordix Licenses to ONAP guidelines
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsDataPersistenceServiceSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Pantheon.tech
5  *  Modifications Copyright (C) 2021 Bell Canada.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22 package org.onap.cps.spi.impl
23
24 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
25 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
26
27 import com.google.common.collect.ImmutableSet
28 import com.google.gson.Gson
29 import com.google.gson.GsonBuilder
30 import org.onap.cps.spi.CpsDataPersistenceService
31 import org.onap.cps.spi.entities.FragmentEntity
32 import org.onap.cps.spi.exceptions.AlreadyDefinedException
33 import org.onap.cps.spi.exceptions.AnchorNotFoundException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
36 import org.onap.cps.spi.model.DataNode
37 import org.onap.cps.spi.model.DataNodeBuilder
38 import org.springframework.beans.factory.annotation.Autowired
39 import org.springframework.test.context.jdbc.Sql
40
41 import javax.validation.ConstraintViolationException
42
43 class CpsDataPersistenceServiceSpec extends CpsPersistenceSpecBase {
44
45     @Autowired
46     CpsDataPersistenceService objectUnderTest
47
48     static final Gson GSON = new GsonBuilder().create()
49
50     static final String SET_DATA = '/data/fragment.sql'
51     static final long ID_DATA_NODE_WITH_DESCENDANTS = 4001
52     static final String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
53     static final String XPATH_DATA_NODE_WITH_LEAVES = '/parent-100'
54     static final long UPDATE_DATA_NODE_FRAGMENT_ID = 4202L
55     static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L
56     static final long LIST_DATA_NODE_PARENT_FRAGMENT_ID = 4206L
57
58     static final DataNode newDataNode = new DataNodeBuilder().build()
59     static DataNode existingDataNode
60     static DataNode existingChildDataNode
61
62     def expectedLeavesByXpathMap = [
63             '/parent-100'                      : ['parent-leaf': 'parent-leaf value'],
64             '/parent-100/child-001'            : ['first-child-leaf': 'first-child-leaf value'],
65             '/parent-100/child-002'            : ['second-child-leaf': 'second-child-leaf value'],
66             '/parent-100/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
67     ]
68
69     static {
70         existingDataNode = createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)
71         existingChildDataNode = createDataNodeTree('/parent-1/child-1')
72     }
73
74     @Sql([CLEAR_DATA, SET_DATA])
75     def 'StoreDataNode with descendants.'() {
76         when: 'a fragment with descendants is stored'
77             def parentXpath = "/parent-new"
78             def childXpath = "/parent-new/child-new"
79             def grandChildXpath = "/parent-new/child-new/grandchild-new"
80             objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1,
81                     createDataNodeTree(parentXpath, childXpath, grandChildXpath))
82         then: 'it can be retrieved by its xpath'
83             def parentFragment = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, parentXpath)
84         and: 'it contains the children'
85             parentFragment.childFragments.size() == 1
86             def childFragment = parentFragment.childFragments[0]
87             childFragment.xpath == childXpath
88         and: "and its children's children"
89             childFragment.childFragments.size() == 1
90             def grandchildFragment = childFragment.childFragments[0]
91             grandchildFragment.xpath == grandChildXpath
92     }
93
94     @Sql([CLEAR_DATA, SET_DATA])
95     def 'Store data node for multiple anchors using the same schema.'() {
96         def xpath = "/parent-new"
97         given: 'a fragment is stored for an anchor'
98             objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1, createDataNodeTree(xpath))
99         when: 'another fragment is stored for an other anchor, using the same schema set'
100             objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME3, createDataNodeTree(xpath))
101         then: 'both fragments can be retrieved by their xpath'
102             def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
103             fragment1.anchor.name == ANCHOR_NAME1
104             fragment1.xpath == xpath
105             def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
106             fragment2.anchor.name == ANCHOR_NAME3
107             fragment2.xpath == xpath
108     }
109
110     @Sql([CLEAR_DATA, SET_DATA])
111     def 'Store datanode error scenario: #scenario.'() {
112         when: 'attempt to store a data node with #scenario'
113             objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
114         then: 'a #expectedException is thrown'
115             thrown(expectedException)
116         where: 'the following data is used'
117             scenario                    | dataspaceName  | anchorName     | dataNode         || expectedException
118             'dataspace does not exist'  | 'unknown'      | 'not-relevant' | newDataNode      || DataspaceNotFoundException
119             'schema set does not exist' | DATASPACE_NAME | 'unknown'      | newDataNode      || AnchorNotFoundException
120             'anchor already exists'     | DATASPACE_NAME | ANCHOR_NAME1   | newDataNode      || ConstraintViolationException
121             'datanode already exists'   | DATASPACE_NAME | ANCHOR_NAME1   | existingDataNode || AlreadyDefinedException
122     }
123
124     @Sql([CLEAR_DATA, SET_DATA])
125     def 'Add a child to a Fragment that already has a child.'() {
126         given: ' a new child node'
127             def newChild = createDataNodeTree('xpath for new child')
128         when: 'the child is added to an existing parent with 1 child'
129             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
130         then: 'the parent is now has to 2 children'
131             def expectedExistingChildPath = '/parent-1/child-1'
132             def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
133             parentFragment.getChildFragments().size() == 2
134         and: 'it still has the old child'
135             parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
136         and: 'it has the new child'
137             parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
138     }
139
140     @Sql([CLEAR_DATA, SET_DATA])
141     def 'Add child error scenario: #scenario.'() {
142         when: 'attempt to add a child data node with #scenario'
143             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
144         then: 'a #expectedException is thrown'
145             thrown(expectedException)
146         where: 'the following data is used'
147             scenario                 | parentXpath                      | dataNode              || expectedException
148             'parent does not exist'  | 'unknown'                        | newDataNode           || DataNodeNotFoundException
149             'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || AlreadyDefinedException
150     }
151
152     @Sql([CLEAR_DATA, SET_DATA])
153     def 'Add list-node fragment with multiple elements.'() {
154         given: 'list node data fragment as a collection of data nodes'
155             def listNodeXpaths = ['/parent-201/child-204[@key="B"]', '/parent-201/child-204[@key="C"]']
156             def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
157         when: 'list-node elements added to existing parent node'
158             objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
159         then: 'new entries successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
160             def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
161             def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
162             assert allChildXpaths.size() == 5
163             assert allChildXpaths.containsAll(listNodeXpaths)
164     }
165
166     @Sql([CLEAR_DATA, SET_DATA])
167     def 'Add list-node fragment error scenario: #scenario.'() {
168         given: 'list node data fragment as a collection of data nodes'
169             def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
170         when: 'list-node elements added to existing parent node'
171             objectUnderTest.addListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
172         then: 'a #expectedException is thrown'
173             thrown(expectedException)
174         where: 'following parameters were used'
175             scenario                     | parentNodeXpath | listNodeXpaths                      || expectedException
176             'parent node does not exist' | '/unknown'      | ['irrelevant']                      || DataNodeNotFoundException
177             'already existing fragment'  | '/parent-201'   | ['/parent-201/child-204[@key="A"]'] || AlreadyDefinedException
178
179     }
180
181     static def createDataNodeTree(String... xpaths) {
182         def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
183         if (xpaths.length > 1) {
184             def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
185             def childDataNode = createDataNodeTree(xPathsDescendant)
186             dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
187         }
188         dataNodeBuilder.build()
189     }
190
191     def getFragmentByXpath(dataspaceName, anchorName, xpath) {
192         def dataspace = dataspaceRepository.getByName(dataspaceName)
193         def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
194         return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
195     }
196
197     @Sql([CLEAR_DATA, SET_DATA])
198     def 'Get data node by xpath without descendants.'() {
199         when: 'data node is requested'
200             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
201                     inputXPath, OMIT_DESCENDANTS)
202         then: 'data node is returned with no descendants'
203             assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
204         and: 'expected leaves'
205             assert result.getChildDataNodes().size() == 0
206             assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
207         where: 'the following data is used'
208             scenario      | inputXPath
209             'some xpath'  | '/parent-100'
210             'root xpath'  | '/'
211             'empty xpath' | ''
212     }
213
214     @Sql([CLEAR_DATA, SET_DATA])
215     def 'Get data node by xpath with all descendants.'() {
216         when: 'data node is requested with all descendants'
217             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
218                     inputXPath, INCLUDE_ALL_DESCENDANTS)
219             def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
220         then: 'data node is returned with all the descendants populated'
221             assert mappedResult.size() == 4
222             assert result.getChildDataNodes().size() == 2
223             assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
224             assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
225         and: 'extracted leaves maps are matching expected'
226             mappedResult.forEach(
227                     (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath]))
228         where: 'the following data is used'
229             scenario      | inputXPath
230             'some xpath'  | '/parent-100'
231             'root xpath'  | '/'
232             'empty xpath' | ''
233     }
234
235     @Sql([CLEAR_DATA, SET_DATA])
236     def 'Get data node error scenario: #scenario.'() {
237         when: 'attempt to get data node with #scenario'
238             objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
239         then: 'a #expectedException is thrown'
240             thrown(expectedException)
241         where: 'the following data is used'
242             scenario                 | dataspaceName  | anchorName                        | xpath          || expectedException
243             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant' || DataspaceNotFoundException
244             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant' || AnchorNotFoundException
245             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH'     || DataNodeNotFoundException
246     }
247
248     @Sql([CLEAR_DATA, SET_DATA])
249     def 'Update data node leaves.'() {
250         when: 'update is performed for leaves'
251             objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
252                     "/parent-200/child-201", ['leaf-value': 'new'])
253         then: 'leaves are updated for selected data node'
254             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
255             def updatedLeaves = getLeavesMap(updatedFragment)
256             assert updatedLeaves.size() == 1
257             assert updatedLeaves.'leaf-value' == 'new'
258         and: 'existing child entry remains as is'
259             def childFragment = updatedFragment.getChildFragments().iterator().next()
260             def childLeaves = getLeavesMap(childFragment)
261             assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
262             assert childLeaves.'leaf-value' == 'original'
263     }
264
265     @Sql([CLEAR_DATA, SET_DATA])
266     def 'Update data leaves error scenario: #scenario.'() {
267         when: 'attempt to update data node for #scenario'
268             objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
269         then: 'a #expectedException is thrown'
270             thrown(expectedException)
271         where: 'the following data is used'
272             scenario                 | dataspaceName  | anchorName                        | xpath                || expectedException
273             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant'       || DataspaceNotFoundException
274             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant'       || AnchorNotFoundException
275             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
276     }
277
278     @Sql([CLEAR_DATA, SET_DATA])
279     def 'Replace data node tree with descendants removal.'() {
280         given: 'data node object with leaves updated, no children'
281             def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
282         when: 'replace data node tree is performed'
283             objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
284         then: 'leaves have been updated for selected data node'
285             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
286             def updatedLeaves = getLeavesMap(updatedFragment)
287             assert updatedLeaves.size() == 1
288             assert updatedLeaves.'leaf-value' == 'new'
289         and: 'updated entry has no children'
290             updatedFragment.getChildFragments().isEmpty()
291         and: 'previously attached child entry is removed from database'
292             fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
293     }
294
295     @Sql([CLEAR_DATA, SET_DATA])
296     def 'Replace data node tree with descendants.'() {
297         given: 'data node object with leaves updated, having child with old content'
298             def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
299                     buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
300             ])
301         when: 'update is performed including descendants'
302             objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
303         then: 'leaves have been updated for selected data node'
304             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
305             def updatedLeaves = getLeavesMap(updatedFragment)
306             assert updatedLeaves.size() == 1
307             assert updatedLeaves.'leaf-value' == 'new'
308         and: 'previously attached child entry is removed from database'
309             fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
310         and: 'new child entry with same content is created'
311             def childFragment = updatedFragment.getChildFragments().iterator().next()
312             def childLeaves = getLeavesMap(childFragment)
313             assert childFragment.getId() != UPDATE_DATA_NODE_SUB_FRAGMENT_ID
314             assert childLeaves.'leaf-value' == 'original'
315     }
316
317     @Sql([CLEAR_DATA, SET_DATA])
318     def 'Replace data node tree error scenario: #scenario.'() {
319         given: 'data node object'
320             def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
321         when: 'attempt to update data node for #scenario'
322             objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
323         then: 'a #expectedException is thrown'
324             thrown(expectedException)
325         where: 'the following data is used'
326             scenario                 | dataspaceName  | anchorName                        | xpath                || expectedException
327             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant'       || DataspaceNotFoundException
328             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant'       || AnchorNotFoundException
329             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
330     }
331
332     @Sql([CLEAR_DATA, SET_DATA])
333     def 'Replace list-node content of #scenario.'() {
334         given: 'list node data fragment as a collection of data nodes'
335             def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
336         when: 'list-node elements replaced within the existing parent node'
337             objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', listNodeCollection)
338         then: 'child list elements are updated as expected, non-list element remains as is'
339             def parentFragment = fragmentRepository.getOne(LIST_DATA_NODE_PARENT_FRAGMENT_ID)
340             def allChildXpaths = parentFragment.getChildFragments().collect { it.getXpath() }
341             assert allChildXpaths.size() == expectedChildXpaths.size()
342             assert allChildXpaths.containsAll(expectedChildXpaths)
343         where: 'following parameters were used'
344             scenario                 | listNodeXpaths                      || expectedChildXpaths
345             'existing list-node'     | ['/parent-201/child-204[@key="B"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="B"]']
346             'non-existing list-node' | ['/parent-201/child-205[@key="1"]'] || ['/parent-201/child-203', '/parent-201/child-204[@key="A"]', '/parent-201/child-204[@key="X"]', '/parent-201/child-205[@key="1"]']
347     }
348
349     @Sql([CLEAR_DATA, SET_DATA])
350     def 'Replace list-node fragment error scenario: #scenario.'() {
351         given: 'list node data fragment as a collection of data nodes'
352             def listNodeCollection = buildDataNodeCollection(listNodeXpaths)
353         when: 'list-node elements were replaced under existing parent node'
354             objectUnderTest.replaceListDataNodes(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listNodeCollection)
355         then: 'a #expectedException is thrown'
356             thrown(expectedException)
357         where: 'following parameters were used'
358             scenario                     | parentNodeXpath | listNodeXpaths || expectedException
359             'parent node does not exist' | '/unknown'      | ['irrelevant'] || DataNodeNotFoundException
360     }
361
362     static Collection<DataNode> buildDataNodeCollection(xpaths) {
363         return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
364     }
365
366     static DataNode buildDataNode(xpath, leaves, childDataNodes) {
367         return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
368     }
369
370     static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
371         return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
372     }
373
374     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
375         expectedLeavesMap.forEach((key, value) -> {
376             def actualValue = actualLeavesMap[key]
377             if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
378                 assert value.size() == actualValue.size()
379                 assert value.containsAll(actualValue)
380             } else {
381                 assert value == actualValue
382             }
383         })
384         return true
385     }
386
387     def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
388         flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
389         dataNodeTree.getChildDataNodes()
390                 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
391         return flatMap
392     }
393
394 }