[CPS] RI, Service: Code Refactoring
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsDataPersistenceServiceSpec.groovy
index ac66e8c..204b934 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Copyright (c) 2021 Bell Canada.
  * Modifications Copyright (C) 2021-2023 Nordix Foundation
- * Modifications Copyright (C) 2022 TechMahindra Ltd.
+ * 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.
@@ -24,7 +24,9 @@ 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.entities.FragmentExtract
 import org.onap.cps.spi.exceptions.ConcurrencyException
 import org.onap.cps.spi.exceptions.DataValidationException
 import org.onap.cps.spi.model.DataNode
@@ -48,6 +50,12 @@ class CpsDataPersistenceServiceSpec extends Specification {
     def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
             mockFragmentRepository, jsonObjectMapper, mockSessionManager))
 
+    def anchorEntity = new AnchorEntity(id: 123, dataspace: new DataspaceEntity(id: 1))
+
+    def setup() {
+        mockAnchorRepository.getByDataspaceAndName(_, _) >> anchorEntity
+    }
+
     def 'Storing data nodes individually when batch operation fails'(){
         given: 'two data nodes and supporting repository mock behavior'
             def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
@@ -57,7 +65,7 @@ class CpsDataPersistenceServiceSpec extends Specification {
         when: 'trying to store data nodes'
             objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
         then: 'the two data nodes are saved individually'
-            2 * mockFragmentRepository.save(_);
+            2 * mockFragmentRepository.save(_)
     }
 
     def 'Store single data node.'() {
@@ -69,34 +77,16 @@ class CpsDataPersistenceServiceSpec extends Specification {
             1 * objectUnderTest.storeDataNodes('dataspace1', 'anchor1', [dataNode])
     }
 
-    def 'Handling of StaleStateException (caused by concurrent updates) during update data node and descendants.'() {
-        given: 'the fragment repository returns a fragment entity'
-            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(*_) >> {
-                def fragmentEntity = new FragmentEntity()
-                fragmentEntity.setChildFragments([new FragmentEntity()] as Set<FragmentEntity>)
-                return fragmentEntity
-            }
-        and: 'a data node is concurrently updated by another transaction'
-            mockFragmentRepository.save(_) >> { throw new StaleStateException("concurrent updates") }
-        when: 'attempt to update data node with submitted data nodes'
-            objectUnderTest.updateDataNodeAndDescendants('some-dataspace', 'some-anchor', new DataNodeBuilder().withXpath('/some/xpath').build())
-        then: 'concurrency exception is thrown'
-            def concurrencyException = thrown(ConcurrencyException)
-            assert concurrencyException.getDetails().contains('some-dataspace')
-            assert concurrencyException.getDetails().contains('some-anchor')
-            assert concurrencyException.getDetails().contains('/some/xpath')
-    }
-
     def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
-        given: 'the system contains and can update one datanode'
-            def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('/node1', 'OK')
-        and: 'the system contains two more datanodes that throw an exception while updating'
-            def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('/node2', 'EXCEPTION')
-            def dataNode3 = createDataNodeAndMockRepositoryMethodSupportingIt('/node3', 'EXCEPTION')
+        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', [dataNode1, dataNode2, dataNode3])
+            objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
         then: 'concurrency exception is thrown'
             def thrown = thrown(ConcurrencyException)
             assert thrown.message == 'Concurrent Transactions'
@@ -142,13 +132,11 @@ class CpsDataPersistenceServiceSpec extends Specification {
     }
 
     def 'Retrieving multiple data nodes.'() {
-        given: 'db contains an anchor'
-           def anchorEntity = new AnchorEntity(id:123)
-           mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
-        and: 'fragment repository returns a collection of fragments'
-            def fragmentEntity1 = new FragmentEntity(xpath: '/xpath1', childFragments: [])
-            def fragmentEntity2 = new FragmentEntity(xpath: '/xpath2', childFragments: [])
-            mockFragmentRepository.findByAnchorAndMultipleCpsPaths(123, ['/xpath1', '/xpath2'] as Set<String>) >> [fragmentEntity1, fragmentEntity2]
+        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'
@@ -180,7 +168,7 @@ class CpsDataPersistenceServiceSpec extends Specification {
 
     def 'update data node leaves: #scenario'(){
         given: 'A node exists for the given xpath'
-            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/some/xpath') >> new FragmentEntity(xpath: '/some/xpath', attributes:  existingAttributes)
+            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'
@@ -198,8 +186,11 @@ class CpsDataPersistenceServiceSpec extends Specification {
     }
 
     def 'update data node and descendants: #scenario'(){
-        given: 'mocked responses'
-            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath') >> new FragmentEntity(xpath: '/test/xpath', childFragments: [])
+        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'
@@ -211,9 +202,11 @@ class CpsDataPersistenceServiceSpec extends Specification {
     }
 
     def 'update data nodes and descendants'() {
-        given: 'the fragment repository returns a fragment entity related to the xpath input'
-            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath1') >> new FragmentEntity(xpath: '/test/xpath1', childFragments: [])
-            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath2') >> new FragmentEntity(xpath: '/test/xpath2', childFragments: [])
+        given: 'the fragment repository returns fragment entities related to the xpath inputs'
+            mockFragmentRepository.findExtractsWithDescendants(123, ['/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'])])
@@ -232,18 +225,48 @@ class CpsDataPersistenceServiceSpec extends Specification {
     def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
         def dataNode = new DataNodeBuilder().withXpath(xpath).build()
         def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
-        mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
+        mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
         if ('EXCEPTION' == scenario) {
             mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
         }
         return dataNode
     }
 
+    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, null, xpath, null)
+            fragmentExtracts.add(fragmentExtract)
+            def fragmentEntity = new FragmentEntity(id: fragmentId, xpath: xpath, childFragments: [])
+            mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
+            if ('EXCEPTION' == scenario) {
+                mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
+            }
+            fragmentId++
+        }
+        mockFragmentRepository.findExtractsWithDescendants(_, xpathToScenarioMap.keySet(), _) >> fragmentExtracts
+        return dataNodes
+    }
+
     def mockFragmentWithJson(json) {
-        def anchorEntity = new AnchorEntity(id:123)
-        mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
-        def fragmentEntity = new FragmentEntity(xpath: '/parent-01', childFragments: [], attributes: json)
-        mockFragmentRepository.findByAnchorAndMultipleCpsPaths(123, ['/parent-01'] as Set<String>) >> [fragmentEntity]
+        def fragmentExtract = mockFragmentExtract(456, null, 123, '/parent-01', json)
+        mockFragmentRepository.findExtractsWithDescendants(123, ['/parent-01'] as Set, _) >> [fragmentExtract]
+    }
+
+    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
     }
 
 }