Implement ends with cps path query to support multiple attributes with 'and' condition
[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  *  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 package org.onap.cps.spi.impl
22
23 import com.google.common.collect.ImmutableSet
24 import com.google.gson.Gson
25 import com.google.gson.GsonBuilder
26 import org.onap.cps.spi.CpsDataPersistenceService
27 import org.onap.cps.spi.entities.FragmentEntity
28 import org.onap.cps.spi.exceptions.AlreadyDefinedException
29 import org.onap.cps.spi.exceptions.AnchorNotFoundException
30 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
31 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
32 import org.onap.cps.spi.model.DataNode
33 import org.onap.cps.spi.model.DataNodeBuilder
34 import org.springframework.beans.factory.annotation.Autowired
35 import org.springframework.dao.DataIntegrityViolationException
36 import org.springframework.test.context.jdbc.Sql
37 import spock.lang.Unroll
38
39 import javax.validation.ConstraintViolationException
40
41 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
42 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
43
44 class CpsDataPersistenceServiceSpec extends CpsPersistenceSpecBase {
45
46     @Autowired
47     CpsDataPersistenceService objectUnderTest
48
49     static final Gson GSON = new GsonBuilder().create()
50
51     static final String SET_DATA = '/data/fragment.sql'
52     static final long ID_DATA_NODE_WITH_DESCENDANTS = 4001
53     static final String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
54     static final String XPATH_DATA_NODE_WITH_LEAVES = '/parent-100'
55     static final long UPDATE_DATA_NODE_FRAGMENT_ID = 4202L
56     static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L
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     @Unroll
111     @Sql([CLEAR_DATA, SET_DATA])
112     def 'Store datanode error scenario: #scenario.'() {
113         when: 'attempt to store a data node with #scenario'
114             objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
115         then: 'a #expectedException is thrown'
116             thrown(expectedException)
117         where: 'the following data is used'
118             scenario                    | dataspaceName  | anchorName     | dataNode         || expectedException
119             'dataspace does not exist'  | 'unknown'      | 'not-relevant' | newDataNode      || DataspaceNotFoundException
120             'schema set does not exist' | DATASPACE_NAME | 'unknown'      | newDataNode      || AnchorNotFoundException
121             'anchor already exists'     | DATASPACE_NAME | ANCHOR_NAME1   | newDataNode      || ConstraintViolationException
122             'datanode already exists'   | DATASPACE_NAME | ANCHOR_NAME1   | existingDataNode || AlreadyDefinedException
123     }
124
125     @Sql([CLEAR_DATA, SET_DATA])
126     def 'Add a child to a Fragment that already has a child.'() {
127         given: ' a new child node'
128             def newChild = createDataNodeTree('xpath for new child')
129         when: 'the child is added to an existing parent with 1 child'
130             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
131         then: 'the parent is now has to 2 children'
132             def expectedExistingChildPath = '/parent-1/child-1'
133             def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
134             parentFragment.getChildFragments().size() == 2
135         and: 'it still has the old child'
136             parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
137         and: 'it has the new child'
138             parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
139     }
140
141     @Unroll
142     @Sql([CLEAR_DATA, SET_DATA])
143     def 'Add child error scenario: #scenario.'() {
144         when: 'attempt to add a child data node with #scenario'
145             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
146         then: 'a #expectedException is thrown'
147             thrown(expectedException)
148         where: 'the following data is used'
149             scenario                 | parentXpath                      | dataNode              || expectedException
150             'parent does not exist'  | 'unknown'                        | newDataNode           || DataNodeNotFoundException
151             'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || DataIntegrityViolationException
152     }
153
154     static def createDataNodeTree(String... xpaths) {
155         def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
156         if (xpaths.length > 1) {
157             def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
158             def childDataNode = createDataNodeTree(xPathsDescendant)
159             dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
160         }
161         dataNodeBuilder.build()
162     }
163
164     def getFragmentByXpath(dataspaceName, anchorName, xpath) {
165         def dataspace = dataspaceRepository.getByName(dataspaceName)
166         def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
167         return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
168     }
169
170     @Sql([CLEAR_DATA, SET_DATA])
171     def 'Get data node by xpath without descendants.'() {
172         when: 'data node is requested'
173             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
174                     XPATH_DATA_NODE_WITH_LEAVES, OMIT_DESCENDANTS)
175         then: 'data node is returned with no descendants'
176             assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
177         and: 'expected leaves'
178             assert result.getChildDataNodes().size() == 0
179             assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
180     }
181
182     @Sql([CLEAR_DATA, SET_DATA])
183     def 'Get data node by xpath with all descendants.'() {
184         when: 'data node is requested with all descendants'
185             def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
186                     XPATH_DATA_NODE_WITH_LEAVES, INCLUDE_ALL_DESCENDANTS)
187             def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
188         then: 'data node is returned with all the descendants populated'
189             assert mappedResult.size() == 4
190             assert result.getChildDataNodes().size() == 2
191             assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
192             assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
193         and: 'extracted leaves maps are matching expected'
194             mappedResult.forEach(
195                     (xpath, dataNode) ->
196                             assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xpath])
197             )
198     }
199
200     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
201         expectedLeavesMap.forEach((key, value) -> {
202             def actualValue = actualLeavesMap[key]
203             if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
204                 assert value.size() == actualValue.size()
205                 assert value.containsAll(actualValue)
206             } else {
207                 assert value == actualValue
208             }
209         }
210         )
211         return true
212     }
213
214     def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
215         flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
216         dataNodeTree.getChildDataNodes()
217                 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
218         return flatMap
219     }
220
221     @Unroll
222     @Sql([CLEAR_DATA, SET_DATA])
223     def 'Get data node error scenario: #scenario.'() {
224         when: 'attempt to get data node with #scenario'
225             objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
226         then: 'a #expectedException is thrown'
227             thrown(expectedException)
228         where: 'the following data is used'
229             scenario                 | dataspaceName  | anchorName                        | xpath          || expectedException
230             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant' || DataspaceNotFoundException
231             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant' || AnchorNotFoundException
232             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH'     || DataNodeNotFoundException
233     }
234
235     @Sql([CLEAR_DATA, SET_DATA])
236     def 'Update data node leaves.'() {
237         when: 'update is performed for leaves'
238             objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
239                     "/parent-200/child-201", ['leaf-value': 'new'])
240         then: 'leaves are updated for selected data node'
241             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
242             def updatedLeaves = getLeavesMap(updatedFragment)
243             assert updatedLeaves.size() == 1
244             assert updatedLeaves.'leaf-value' == 'new'
245         and: 'existing child entry remains as is'
246             def childFragment = updatedFragment.getChildFragments().iterator().next()
247             def childLeaves = getLeavesMap(childFragment)
248             assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
249             assert childLeaves.'leaf-value' == 'original'
250     }
251
252     @Unroll
253     @Sql([CLEAR_DATA, SET_DATA])
254     def 'Update data leaves error scenario: #scenario.'() {
255         when: 'attempt to update data node for #scenario'
256             objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
257         then: 'a #expectedException is thrown'
258             thrown(expectedException)
259         where: 'the following data is used'
260             scenario                 | dataspaceName  | anchorName                        | xpath                || expectedException
261             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant'       || DataspaceNotFoundException
262             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant'       || AnchorNotFoundException
263             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
264     }
265
266     @Sql([CLEAR_DATA, SET_DATA])
267     def 'Replace data node tree with descendants removal.'() {
268         given: 'data node object with leaves updated, no children'
269             def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
270         when: 'replace data node tree is performed'
271             objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
272         then: 'leaves have been updated for selected data node'
273             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
274             def updatedLeaves = getLeavesMap(updatedFragment)
275             assert updatedLeaves.size() == 1
276             assert updatedLeaves.'leaf-value' == 'new'
277         and: 'updated entry has no children'
278             updatedFragment.getChildFragments().isEmpty()
279         and: 'previously attached child entry is removed from database'
280             fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
281     }
282
283     @Sql([CLEAR_DATA, SET_DATA])
284     def 'Replace data node tree with descendants.'() {
285         given: 'data node object with leaves updated, having child with old content'
286             def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
287                     buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
288             ])
289         when: 'update is performed including descendants'
290             objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
291         then: 'leaves have been updated for selected data node'
292             def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
293             def updatedLeaves = getLeavesMap(updatedFragment)
294             assert updatedLeaves.size() == 1
295             assert updatedLeaves.'leaf-value' == 'new'
296         and: 'previously attached child entry is removed from database'
297             fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
298         and: 'new child entry with same content is created'
299             def childFragment = updatedFragment.getChildFragments().iterator().next()
300             def childLeaves = getLeavesMap(childFragment)
301             assert childFragment.getId() != UPDATE_DATA_NODE_SUB_FRAGMENT_ID
302             assert childLeaves.'leaf-value' == 'original'
303     }
304
305     @Unroll
306     @Sql([CLEAR_DATA, SET_DATA])
307     def 'Replace data node tree error scenario: #scenario.'() {
308         given: 'data node object'
309             def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
310         when: 'attempt to update data node for #scenario'
311             objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
312         then: 'a #expectedException is thrown'
313             thrown(expectedException)
314         where: 'the following data is used'
315             scenario                 | dataspaceName  | anchorName                        | xpath                || expectedException
316             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | 'not relevant'       || DataspaceNotFoundException
317             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | 'not relevant'       || AnchorNotFoundException
318             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
319     }
320
321     static DataNode buildDataNode(xpath, leaves, childDataNodes) {
322         return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
323     }
324
325     static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
326         return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
327     }
328 }