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
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
21 package org.onap.cps.spi.impl
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
38 import javax.validation.ConstraintViolationException
40 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
41 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
43 class CpsDataPersistenceServiceSpec extends CpsPersistenceSpecBase {
46 CpsDataPersistenceService objectUnderTest
48 static final Gson GSON = new GsonBuilder().create()
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
57 static final DataNode newDataNode = new DataNodeBuilder().build()
58 static DataNode existingDataNode
59 static DataNode existingChildDataNode
61 def expectedLeavesByXpathMap = [
62 '/parent-100' : ['parent-leaf': 'parent-leaf value'],
63 '/parent-100/child-001' : ['first-child-leaf': 'first-child-leaf value'],
64 '/parent-100/child-002' : ['second-child-leaf': 'second-child-leaf value'],
65 '/parent-100/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
69 existingDataNode = createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)
70 existingChildDataNode = createDataNodeTree('/parent-1/child-1')
73 @Sql([CLEAR_DATA, SET_DATA])
74 def 'StoreDataNode with descendants.'() {
75 when: 'a fragment with descendants is stored'
76 def parentXpath = "/parent-new"
77 def childXpath = "/parent-new/child-new"
78 def grandChildXpath = "/parent-new/child-new/grandchild-new"
79 objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1,
80 createDataNodeTree(parentXpath, childXpath, grandChildXpath))
81 then: 'it can be retrieved by its xpath'
82 def parentFragment = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, parentXpath)
83 and: 'it contains the children'
84 parentFragment.childFragments.size() == 1
85 def childFragment = parentFragment.childFragments[0]
86 childFragment.xpath == childXpath
87 and: "and its children's children"
88 childFragment.childFragments.size() == 1
89 def grandchildFragment = childFragment.childFragments[0]
90 grandchildFragment.xpath == grandChildXpath
93 @Sql([CLEAR_DATA, SET_DATA])
94 def 'Store data node for multiple anchors using the same schema.'() {
95 def xpath = "/parent-new"
96 given: 'a fragment is stored for an anchor'
97 objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1, createDataNodeTree(xpath))
98 when: 'another fragment is stored for an other anchor, using the same schema set'
99 objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME3, createDataNodeTree(xpath))
100 then: 'both fragments can be retrieved by their xpath'
101 def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
102 fragment1.anchor.name == ANCHOR_NAME1
103 fragment1.xpath == xpath
104 def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
105 fragment2.anchor.name == ANCHOR_NAME3
106 fragment2.xpath == xpath
109 @Sql([CLEAR_DATA, SET_DATA])
110 def 'Store datanode error scenario: #scenario.'() {
111 when: 'attempt to store a data node with #scenario'
112 objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
113 then: 'a #expectedException is thrown'
114 thrown(expectedException)
115 where: 'the following data is used'
116 scenario | dataspaceName | anchorName | dataNode || expectedException
117 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNode || DataspaceNotFoundException
118 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNode || AnchorNotFoundException
119 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNode || ConstraintViolationException
120 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNode || AlreadyDefinedException
123 @Sql([CLEAR_DATA, SET_DATA])
124 def 'Add a child to a Fragment that already has a child.'() {
125 given: ' a new child node'
126 def newChild = createDataNodeTree('xpath for new child')
127 when: 'the child is added to an existing parent with 1 child'
128 objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
129 then: 'the parent is now has to 2 children'
130 def expectedExistingChildPath = '/parent-1/child-1'
131 def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
132 parentFragment.getChildFragments().size() == 2
133 and: 'it still has the old child'
134 parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
135 and: 'it has the new child'
136 parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
139 @Sql([CLEAR_DATA, SET_DATA])
140 def 'Add child error scenario: #scenario.'() {
141 when: 'attempt to add a child data node with #scenario'
142 objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
143 then: 'a #expectedException is thrown'
144 thrown(expectedException)
145 where: 'the following data is used'
146 scenario | parentXpath | dataNode || expectedException
147 'parent does not exist' | 'unknown' | newDataNode || DataNodeNotFoundException
148 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || DataIntegrityViolationException
151 static def createDataNodeTree(String... xpaths) {
152 def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
153 if (xpaths.length > 1) {
154 def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
155 def childDataNode = createDataNodeTree(xPathsDescendant)
156 dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
158 dataNodeBuilder.build()
161 def getFragmentByXpath(dataspaceName, anchorName, xpath) {
162 def dataspace = dataspaceRepository.getByName(dataspaceName)
163 def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
164 return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
167 @Sql([CLEAR_DATA, SET_DATA])
168 def 'Get data node by xpath without descendants.'() {
169 when: 'data node is requested'
170 def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
171 inputXPath, OMIT_DESCENDANTS)
172 then: 'data node is returned with no descendants'
173 assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
174 and: 'expected leaves'
175 assert result.getChildDataNodes().size() == 0
176 assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
177 where: 'the following data is used'
178 scenario | inputXPath
179 'some xpath' |'/parent-100'
184 @Sql([CLEAR_DATA, SET_DATA])
185 def 'Get data node by xpath with all descendants.'() {
186 when: 'data node is requested with all descendants'
187 def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
188 inputXPath, INCLUDE_ALL_DESCENDANTS)
189 def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
190 then: 'data node is returned with all the descendants populated'
191 assert mappedResult.size() == 4
192 assert result.getChildDataNodes().size() == 2
193 assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
194 assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
195 and: 'extracted leaves maps are matching expected'
196 mappedResult.forEach(
197 (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath]))
198 where: 'the following data is used'
199 scenario | inputXPath
200 'some xpath' |'/parent-100'
205 @Sql([CLEAR_DATA, SET_DATA])
206 def 'Get data node error scenario: #scenario.'() {
207 when: 'attempt to get data node with #scenario'
208 objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
209 then: 'a #expectedException is thrown'
210 thrown(expectedException)
211 where: 'the following data is used'
212 scenario | dataspaceName | anchorName | xpath || expectedException
213 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
214 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
215 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH' || DataNodeNotFoundException
218 @Sql([CLEAR_DATA, SET_DATA])
219 def 'Update data node leaves.'() {
220 when: 'update is performed for leaves'
221 objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
222 "/parent-200/child-201", ['leaf-value': 'new'])
223 then: 'leaves are updated for selected data node'
224 def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
225 def updatedLeaves = getLeavesMap(updatedFragment)
226 assert updatedLeaves.size() == 1
227 assert updatedLeaves.'leaf-value' == 'new'
228 and: 'existing child entry remains as is'
229 def childFragment = updatedFragment.getChildFragments().iterator().next()
230 def childLeaves = getLeavesMap(childFragment)
231 assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
232 assert childLeaves.'leaf-value' == 'original'
235 @Sql([CLEAR_DATA, SET_DATA])
236 def 'Update data leaves error scenario: #scenario.'() {
237 when: 'attempt to update data node for #scenario'
238 objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
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 | 'NON-EXISTING XPATH' || DataNodeNotFoundException
248 @Sql([CLEAR_DATA, SET_DATA])
249 def 'Replace data node tree with descendants removal.'() {
250 given: 'data node object with leaves updated, no children'
251 def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
252 when: 'replace data node tree is performed'
253 objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
254 then: 'leaves have been updated for selected data node'
255 def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
256 def updatedLeaves = getLeavesMap(updatedFragment)
257 assert updatedLeaves.size() == 1
258 assert updatedLeaves.'leaf-value' == 'new'
259 and: 'updated entry has no children'
260 updatedFragment.getChildFragments().isEmpty()
261 and: 'previously attached child entry is removed from database'
262 fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
265 @Sql([CLEAR_DATA, SET_DATA])
266 def 'Replace data node tree with descendants.'() {
267 given: 'data node object with leaves updated, having child with old content'
268 def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
269 buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
271 when: 'update is performed including descendants'
272 objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
273 then: 'leaves have been updated for selected data node'
274 def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
275 def updatedLeaves = getLeavesMap(updatedFragment)
276 assert updatedLeaves.size() == 1
277 assert updatedLeaves.'leaf-value' == 'new'
278 and: 'previously attached child entry is removed from database'
279 fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
280 and: 'new child entry with same content is created'
281 def childFragment = updatedFragment.getChildFragments().iterator().next()
282 def childLeaves = getLeavesMap(childFragment)
283 assert childFragment.getId() != UPDATE_DATA_NODE_SUB_FRAGMENT_ID
284 assert childLeaves.'leaf-value' == 'original'
287 @Sql([CLEAR_DATA, SET_DATA])
288 def 'Replace data node tree error scenario: #scenario.'() {
289 given: 'data node object'
290 def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
291 when: 'attempt to update data node for #scenario'
292 objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
293 then: 'a #expectedException is thrown'
294 thrown(expectedException)
295 where: 'the following data is used'
296 scenario | dataspaceName | anchorName | xpath || expectedException
297 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
298 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
299 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
302 static DataNode buildDataNode(xpath, leaves, childDataNodes) {
303 return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
306 static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
307 return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
310 def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
311 expectedLeavesMap.forEach((key, value) -> {
312 def actualValue = actualLeavesMap[key]
313 if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
314 assert value.size() == actualValue.size()
315 assert value.containsAll(actualValue)
317 assert value == actualValue
323 def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
324 flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
325 dataNodeTree.getChildDataNodes()
326 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))