/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation
- * Modifications Copyright (C) 2021 Pantheon.tech
- * Modifications Copyright (C) 2021 Bell Canada.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Copyright (c) 2021 Bell Canada.
+ * Modifications Copyright (C) 2021-2023 Nordix Foundation
+ * Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+*/
+
package org.onap.cps.spi.impl
-import com.google.common.collect.ImmutableSet
-import com.google.gson.Gson
-import com.google.gson.GsonBuilder
-import org.onap.cps.spi.CpsDataPersistenceService
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.hibernate.StaleStateException
+import org.onap.cps.spi.FetchDescendantsOption
+import org.onap.cps.spi.entities.AnchorEntity
+import org.onap.cps.spi.entities.DataspaceEntity
import org.onap.cps.spi.entities.FragmentEntity
-import org.onap.cps.spi.exceptions.AlreadyDefinedException
-import org.onap.cps.spi.exceptions.AnchorNotFoundException
-import org.onap.cps.spi.exceptions.DataNodeNotFoundException
-import org.onap.cps.spi.exceptions.DataspaceNotFoundException
+import org.onap.cps.spi.entities.FragmentExtract
+import org.onap.cps.spi.exceptions.ConcurrencyException
+import org.onap.cps.spi.exceptions.DataValidationException
import org.onap.cps.spi.model.DataNode
import org.onap.cps.spi.model.DataNodeBuilder
-import org.springframework.beans.factory.annotation.Autowired
+import org.onap.cps.spi.repository.AnchorRepository
+import org.onap.cps.spi.repository.DataspaceRepository
+import org.onap.cps.spi.repository.FragmentRepository
+import org.onap.cps.spi.utils.SessionManager
+import org.onap.cps.utils.JsonObjectMapper
import org.springframework.dao.DataIntegrityViolationException
-import org.springframework.test.context.jdbc.Sql
-
-import javax.validation.ConstraintViolationException
-
-import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
-import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
-
-class CpsDataPersistenceServiceSpec extends CpsPersistenceSpecBase {
-
- @Autowired
- CpsDataPersistenceService objectUnderTest
-
- static final Gson GSON = new GsonBuilder().create()
-
- static final String SET_DATA = '/data/fragment.sql'
- static final long ID_DATA_NODE_WITH_DESCENDANTS = 4001
- static final String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
- static final String XPATH_DATA_NODE_WITH_LEAVES = '/parent-100'
- static final long UPDATE_DATA_NODE_FRAGMENT_ID = 4202L
- static final long UPDATE_DATA_NODE_SUB_FRAGMENT_ID = 4203L
-
- static final DataNode newDataNode = new DataNodeBuilder().build()
- static DataNode existingDataNode
- static DataNode existingChildDataNode
+import spock.lang.Specification
- def expectedLeavesByXpathMap = [
- '/parent-100' : ['parent-leaf': 'parent-leaf value'],
- '/parent-100/child-001' : ['first-child-leaf': 'first-child-leaf value'],
- '/parent-100/child-002' : ['second-child-leaf': 'second-child-leaf value'],
- '/parent-100/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
- ]
+class CpsDataPersistenceServiceSpec extends Specification {
- static {
- existingDataNode = createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)
- existingChildDataNode = createDataNodeTree('/parent-1/child-1')
- }
+ def mockDataspaceRepository = Mock(DataspaceRepository)
+ def mockAnchorRepository = Mock(AnchorRepository)
+ def mockFragmentRepository = Mock(FragmentRepository)
+ def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
+ def mockSessionManager = Mock(SessionManager)
- @Sql([CLEAR_DATA, SET_DATA])
- def 'StoreDataNode with descendants.'() {
- when: 'a fragment with descendants is stored'
- def parentXpath = "/parent-new"
- def childXpath = "/parent-new/child-new"
- def grandChildXpath = "/parent-new/child-new/grandchild-new"
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1,
- createDataNodeTree(parentXpath, childXpath, grandChildXpath))
- then: 'it can be retrieved by its xpath'
- def parentFragment = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, parentXpath)
- and: 'it contains the children'
- parentFragment.childFragments.size() == 1
- def childFragment = parentFragment.childFragments[0]
- childFragment.xpath == childXpath
- and: "and its children's children"
- childFragment.childFragments.size() == 1
- def grandchildFragment = childFragment.childFragments[0]
- grandchildFragment.xpath == grandChildXpath
- }
+ def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
+ mockFragmentRepository, jsonObjectMapper, mockSessionManager))
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Store data node for multiple anchors using the same schema.'() {
- def xpath = "/parent-new"
- given: 'a fragment is stored for an anchor'
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME1, createDataNodeTree(xpath))
- when: 'another fragment is stored for an other anchor, using the same schema set'
- objectUnderTest.storeDataNode(DATASPACE_NAME, ANCHOR_NAME3, createDataNodeTree(xpath))
- then: 'both fragments can be retrieved by their xpath'
- def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
- fragment1.anchor.name == ANCHOR_NAME1
- fragment1.xpath == xpath
- def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
- fragment2.anchor.name == ANCHOR_NAME3
- fragment2.xpath == xpath
- }
+ static def anchorEntity = new AnchorEntity(id: 123, dataspace: new DataspaceEntity(id: 1))
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Store datanode error scenario: #scenario.'() {
- when: 'attempt to store a data node with #scenario'
- objectUnderTest.storeDataNode(dataspaceName, anchorName, dataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | dataNode || expectedException
- 'dataspace does not exist' | 'unknown' | 'not-relevant' | newDataNode || DataspaceNotFoundException
- 'schema set does not exist' | DATASPACE_NAME | 'unknown' | newDataNode || AnchorNotFoundException
- 'anchor already exists' | DATASPACE_NAME | ANCHOR_NAME1 | newDataNode || ConstraintViolationException
- 'datanode already exists' | DATASPACE_NAME | ANCHOR_NAME1 | existingDataNode || AlreadyDefinedException
+ def setup() {
+ mockAnchorRepository.getByDataspaceAndName(_, _) >> anchorEntity
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add a child to a Fragment that already has a child.'() {
- given: ' a new child node'
- def newChild = createDataNodeTree('xpath for new child')
- when: 'the child is added to an existing parent with 1 child'
- objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChild)
- then: 'the parent is now has to 2 children'
- def expectedExistingChildPath = '/parent-1/child-1'
- def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
- parentFragment.getChildFragments().size() == 2
- and: 'it still has the old child'
- parentFragment.getChildFragments().find({ it.xpath == expectedExistingChildPath })
- and: 'it has the new child'
- parentFragment.getChildFragments().find({ it.xpath == newChild.xpath })
+ def 'Storing data nodes individually when batch operation fails'(){
+ given: 'two data nodes and supporting repository mock behavior'
+ def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
+ def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
+ and: 'the batch store operation will fail'
+ mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
+ when: 'trying to store data nodes'
+ objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
+ then: 'the two data nodes are saved individually'
+ 2 * mockFragmentRepository.save(_)
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Add child error scenario: #scenario.'() {
- when: 'attempt to add a child data node with #scenario'
- objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | parentXpath | dataNode || expectedException
- 'parent does not exist' | 'unknown' | newDataNode || DataNodeNotFoundException
- 'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNode || DataIntegrityViolationException
+ def 'Store single data node.'() {
+ given: 'a data node'
+ def dataNode = new DataNode()
+ when: 'storing a single data node'
+ objectUnderTest.storeDataNode('dataspace1', 'anchor1', dataNode)
+ then: 'the call is redirected to storing a collection of data nodes with just the given data node'
+ 1 * objectUnderTest.storeDataNodes('dataspace1', 'anchor1', [dataNode])
}
- static def createDataNodeTree(String... xpaths) {
- def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
- if (xpaths.length > 1) {
- def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
- def childDataNode = createDataNodeTree(xPathsDescendant)
- dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
- }
- dataNodeBuilder.build()
+ def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
+ given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
+ def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
+ '/node1': 'OK',
+ '/node2': 'EXCEPTION',
+ '/node3': 'EXCEPTION'])
+ and: 'the batch update will therefore also fail'
+ mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
+ when: 'attempt batch update data nodes'
+ objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
+ then: 'concurrency exception is thrown'
+ def thrown = thrown(ConcurrencyException)
+ assert thrown.message == 'Concurrent Transactions'
+ and: 'it does not contain the successfull datanode'
+ assert !thrown.details.contains('/node1')
+ and: 'it contains the failed datanodes'
+ assert thrown.details.contains('/node2')
+ assert thrown.details.contains('/node3')
}
- def getFragmentByXpath(dataspaceName, anchorName, xpath) {
- def dataspace = dataspaceRepository.getByName(dataspaceName)
- def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
- return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
+ def 'Retrieving a data node with a property JSON value of #scenario'() {
+ given: 'the db has a fragment with an attribute property JSON value of #scenario'
+ mockFragmentWithJson("{\"some attribute\": ${dataString}}")
+ when: 'getting the data node represented by this fragment'
+ def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
+ '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
+ then: 'the leaf is of the correct value and data type'
+ def attributeValue = dataNode[0].leaves.get('some attribute')
+ assert attributeValue == expectedValue
+ assert attributeValue.class == expectedDataClass
+ where: 'the following Data Type is passed'
+ scenario | dataString || expectedValue | expectedDataClass
+ 'just numbers' | '15174' || 15174 | Integer
+ 'number with dot' | '15174.32' || 15174.32 | Double
+ 'number with 0 value after dot' | '15174.0' || 15174.0 | Double
+ 'number with 0 value before dot' | '0.32' || 0.32 | Double
+ 'number higher than max int' | '2147483648' || 2147483648 | Long
+ 'just text' | '"Test"' || 'Test' | String
+ 'number with exponent' | '1.2345e5' || 1.2345e5 | Double
+ 'number higher than max int with dot' | '123456789101112.0' || 123456789101112.0 | Double
+ 'text and numbers' | '"String = \'1234\'"' || "String = '1234'" | String
+ 'number as String' | '"12345"' || '12345' | String
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node by xpath without descendants.'() {
- when: 'data node is requested'
- def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- inputXPath, OMIT_DESCENDANTS)
- then: 'data node is returned with no descendants'
- assert result.getXpath() == XPATH_DATA_NODE_WITH_LEAVES
- and: 'expected leaves'
- assert result.getChildDataNodes().size() == 0
- assertLeavesMaps(result.getLeaves(), expectedLeavesByXpathMap[XPATH_DATA_NODE_WITH_LEAVES])
- where: 'the following data is used'
- scenario | inputXPath
- 'some xpath' |'/parent-100'
- 'root xpath' |'/'
- 'empty xpath' |''
+ def 'Retrieving a data node with invalid JSON'() {
+ given: 'a fragment with invalid JSON'
+ mockFragmentWithJson('{invalid json')
+ when: 'getting the data node represented by this fragment'
+ objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
+ '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
+ then: 'a data validation exception is thrown'
+ thrown(DataValidationException)
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node by xpath with all descendants.'() {
- when: 'data node is requested with all descendants'
- def result = objectUnderTest.getDataNode(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- inputXPath, INCLUDE_ALL_DESCENDANTS)
- def mappedResult = treeToFlatMapByXpath(new HashMap<>(), result)
- then: 'data node is returned with all the descendants populated'
- assert mappedResult.size() == 4
- assert result.getChildDataNodes().size() == 2
- assert mappedResult.get('/parent-100/child-001').getChildDataNodes().size() == 0
- assert mappedResult.get('/parent-100/child-002').getChildDataNodes().size() == 1
- and: 'extracted leaves maps are matching expected'
- mappedResult.forEach(
- (xPath, dataNode) -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xPath]))
- where: 'the following data is used'
- scenario | inputXPath
- 'some xpath' |'/parent-100'
- 'root xpath' |'/'
- 'empty xpath' |''
+ def 'Retrieving multiple data nodes.'() {
+ given: 'fragment repository returns a collection of fragments'
+ mockFragmentRepository.findExtractsWithDescendants(123, ['/xpath1', '/xpath2'] as Set, _) >> [
+ mockFragmentExtract(1, null, 123, '/xpath1', null),
+ mockFragmentExtract(2, null, 123, '/xpath2', null)
+ ]
+ when: 'getting data nodes for 2 xpaths'
+ def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
+ then: '2 data nodes are returned'
+ assert result.size() == 2
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Get data node error scenario: #scenario.'() {
- when: 'attempt to get data node with #scenario'
- objectUnderTest.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NO XPATH' || DataNodeNotFoundException
+ def 'start session'() {
+ when: 'start session'
+ objectUnderTest.startSession()
+ then: 'the session manager method to start session is invoked'
+ 1 * mockSessionManager.startSession()
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Update data node leaves.'() {
- when: 'update is performed for leaves'
- objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
- "/parent-200/child-201", ['leaf-value': 'new'])
- then: 'leaves are updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'existing child entry remains as is'
- def childFragment = updatedFragment.getChildFragments().iterator().next()
- def childLeaves = getLeavesMap(childFragment)
- assert childFragment.getId() == UPDATE_DATA_NODE_SUB_FRAGMENT_ID
- assert childLeaves.'leaf-value' == 'original'
+ def 'close session'() {
+ given: 'session ID'
+ def someSessionId = 'someSessionId'
+ when: 'close session method is called with session ID as parameter'
+ objectUnderTest.closeSession(someSessionId)
+ then: 'the session manager method to close session is invoked with parameter'
+ 1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Update data leaves error scenario: #scenario.'() {
- when: 'attempt to update data node for #scenario'
- objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
+ def 'Lock anchor.'(){
+ when: 'lock anchor method is called with anchor entity details'
+ objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
+ then: 'the session manager method to lock anchor is invoked with same parameters'
+ 1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree with descendants removal.'() {
- given: 'data node object with leaves updated, no children'
- def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [])
- when: 'replace data node tree is performed'
- objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
- then: 'leaves have been updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'updated entry has no children'
- updatedFragment.getChildFragments().isEmpty()
- and: 'previously attached child entry is removed from database'
- fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
+ def 'update data node leaves: #scenario'(){
+ given: 'A node exists for the given xpath'
+ mockFragmentRepository.getByAnchorAndXpath(_, '/some/xpath') >> new FragmentEntity(xpath: '/some/xpath', attributes: existingAttributes)
+ when: 'the node leaves are updated'
+ objectUnderTest.updateDataLeaves('some-dataspace', 'some-anchor', '/some/xpath', newAttributes as Map<String, Serializable>)
+ then: 'the fragment entity saved has the original and new attributes'
+ 1 * mockFragmentRepository.save({fragmentEntity -> {
+ assert fragmentEntity.getXpath() == '/some/xpath'
+ assert fragmentEntity.getAttributes() == mergedAttributes
+ }})
+ where: 'the following attributes combinations are used'
+ scenario | existingAttributes | newAttributes | mergedAttributes
+ 'add new leaf' | '{"existing":"value"}' | ["new":"value"] | '{"existing":"value","new":"value"}'
+ 'update existing leaf' | '{"existing":"value"}' | ["existing":"value2"] | '{"existing":"value2"}'
+ 'update nothing with nothing' | '' | [] | ''
+ 'update with nothing' | '{"existing":"value"}' | [] | '{"existing":"value"}'
+ 'update with same value' | '{"existing":"value"}' | ["existing":"value"] | '{"existing":"value"}'
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree with descendants.'() {
- given: 'data node object with leaves updated, having child with old content'
- def submittedDataNode = buildDataNode("/parent-200/child-201", ['leaf-value': 'new'], [
- buildDataNode("/parent-200/child-201/grand-child", ['leaf-value': 'original'], [])
- ])
- when: 'update is performed including descendants'
- objectUnderTest.replaceDataNodeTree(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
- then: 'leaves have been updated for selected data node'
- def updatedFragment = fragmentRepository.getOne(UPDATE_DATA_NODE_FRAGMENT_ID)
- def updatedLeaves = getLeavesMap(updatedFragment)
- assert updatedLeaves.size() == 1
- assert updatedLeaves.'leaf-value' == 'new'
- and: 'previously attached child entry is removed from database'
- fragmentRepository.findById(UPDATE_DATA_NODE_SUB_FRAGMENT_ID).isEmpty()
- and: 'new child entry with same content is created'
- def childFragment = updatedFragment.getChildFragments().iterator().next()
- def childLeaves = getLeavesMap(childFragment)
- assert childFragment.getId() != UPDATE_DATA_NODE_SUB_FRAGMENT_ID
- assert childLeaves.'leaf-value' == 'original'
+ def 'update data node and descendants: #scenario'(){
+ given: 'the fragment repository returns fragment entities related to the xpath inputs'
+ mockFragmentRepository.findExtractsWithDescendants(_, [] as Set, _) >> []
+ mockFragmentRepository.findExtractsWithDescendants(_, ['/test/xpath'] as Set, _) >> [
+ mockFragmentExtract(1, null, 123, '/test/xpath', null)
+ ]
+ when: 'replace data node tree'
+ objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
+ then: 'call fragment repository save all method'
+ 1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
+ where: 'the following Data Type is passed'
+ scenario | dataNodes || expectedFragmentEntities
+ 'empty data node list' | [] || []
+ 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'], childDataNodes: [])] || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', anchor: anchorEntity, childFragments: [])]
}
- @Sql([CLEAR_DATA, SET_DATA])
- def 'Replace data node tree error scenario: #scenario.'() {
- given: 'data node object'
- def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
- when: 'attempt to update data node for #scenario'
- objectUnderTest.replaceDataNodeTree(dataspaceName, anchorName, submittedDataNode)
- then: 'a #expectedException is thrown'
- thrown(expectedException)
- where: 'the following data is used'
- scenario | dataspaceName | anchorName | xpath || expectedException
- 'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' | 'not relevant' || DataspaceNotFoundException
- 'non-existing anchor' | DATASPACE_NAME | 'NO ANCHOR' | 'not relevant' || AnchorNotFoundException
- 'non-existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'NON-EXISTING XPATH' || DataNodeNotFoundException
+ def 'update data nodes and descendants'() {
+ given: 'the fragment repository returns fragment entities related to the xpath inputs'
+ mockFragmentRepository.findExtractsWithDescendants(_, ['/test/xpath1', '/test/xpath2'] as Set, _) >> [
+ mockFragmentExtract(1, null, 123, '/test/xpath1', null),
+ mockFragmentExtract(2, null, 123, '/test/xpath2', null)
+ ]
+ and: 'some data nodes with descendants'
+ def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
+ def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
+ when: 'the fragment entities are update by the data nodes'
+ objectUnderTest.updateDataNodesAndDescendants('dataspace', 'anchor', [dataNode1, dataNode2])
+ then: 'call fragment repository save all method is called with the updated fragments'
+ 1 * mockFragmentRepository.saveAll({fragmentEntities -> {
+ assert fragmentEntities.size() == 2
+ def fragmentEntityPerXpath = fragmentEntities.collectEntries { [it.xpath, it] }
+ assert fragmentEntityPerXpath.get('/test/xpath1').childFragments.first().attributes == '{"id":"childTestId1"}'
+ assert fragmentEntityPerXpath.get('/test/xpath2').childFragments.first().attributes == '{"id":"childTestId2"}'
+ }})
}
- static DataNode buildDataNode(xpath, leaves, childDataNodes) {
- return new DataNodeBuilder().withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
+ def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
+ def dataNode = new DataNodeBuilder().withXpath(xpath).build()
+ def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
+ mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
+ if ('EXCEPTION' == scenario) {
+ mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
+ }
+ return dataNode
}
- static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
- return GSON.fromJson(fragmentEntity.getAttributes(), Map<String, Object>.class)
+ def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
+ def dataNodes = []
+ def fragmentExtracts = []
+ def fragmentId = 1
+ xpathToScenarioMap.each {
+ def xpath = it.key
+ def scenario = it.value
+ def dataNode = new DataNodeBuilder().withXpath(xpath).build()
+ dataNodes.add(dataNode)
+ def fragmentExtract = mockFragmentExtract(fragmentId, null, 123, xpath, null)
+ fragmentExtracts.add(fragmentExtract)
+ def fragmentEntity = new FragmentEntity(id: fragmentId, anchor: anchorEntity, xpath: xpath, childFragments: [])
+ if ('EXCEPTION' == scenario) {
+ mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
+ }
+ fragmentId++
+ }
+ mockFragmentRepository.findExtractsWithDescendants(_, xpathToScenarioMap.keySet(), _) >> fragmentExtracts
+ return dataNodes
}
- def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
- expectedLeavesMap.forEach((key, value) -> {
- def actualValue = actualLeavesMap[key]
- if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
- assert value.size() == actualValue.size()
- assert value.containsAll(actualValue)
- } else {
- assert value == actualValue
- }
- })
- return true
+ def mockFragmentWithJson(json) {
+ def fragmentExtract = mockFragmentExtract(456, null, 123, '/parent-01', json)
+ mockFragmentRepository.findExtractsWithDescendants(123, ['/parent-01'] as Set, _) >> [fragmentExtract]
}
- def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
- flatMap.put(dataNodeTree.getXpath(), dataNodeTree)
- dataNodeTree.getChildDataNodes()
- .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
- return flatMap
+ def mockFragmentExtract(id, parentId, anchorId, xpath, attributes) {
+ def fragmentExtract = Mock(FragmentExtract)
+ fragmentExtract.getId() >> id
+ fragmentExtract.getParentId() >> parentId
+ fragmentExtract.getAnchorId() >> anchorId
+ fragmentExtract.getXpath() >> xpath
+ fragmentExtract.getAttributes() >> attributes
+ return fragmentExtract
}
}