Merge "Use native query to delete data nodes"
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsDataPersistenceServiceSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (c) 2021 Bell Canada.
4  * Modifications Copyright (C) 2021-2023 Nordix Foundation
5  * Modifications Copyright (C) 2022 TechMahindra Ltd.
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  * ============LICENSE_END=========================================================
19 */
20
21 package org.onap.cps.spi.impl
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import org.hibernate.StaleStateException
25 import org.onap.cps.spi.FetchDescendantsOption
26 import org.onap.cps.spi.entities.AnchorEntity
27 import org.onap.cps.spi.entities.FragmentEntity
28 import org.onap.cps.spi.entities.FragmentExtract
29 import org.onap.cps.spi.exceptions.ConcurrencyException
30 import org.onap.cps.spi.exceptions.DataValidationException
31 import org.onap.cps.spi.model.DataNode
32 import org.onap.cps.spi.model.DataNodeBuilder
33 import org.onap.cps.spi.repository.AnchorRepository
34 import org.onap.cps.spi.repository.DataspaceRepository
35 import org.onap.cps.spi.repository.FragmentNativeRepository
36 import org.onap.cps.spi.repository.FragmentRepository
37 import org.onap.cps.spi.utils.SessionManager
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.springframework.dao.DataIntegrityViolationException
40 import spock.lang.Specification
41
42 class CpsDataPersistenceServiceSpec extends Specification {
43
44     def mockDataspaceRepository = Mock(DataspaceRepository)
45     def mockAnchorRepository = Mock(AnchorRepository)
46     def mockFragmentRepository = Mock(FragmentRepository)
47     def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
48     def mockSessionManager = Mock(SessionManager)
49     def stubFragmentNativeRepository = Stub(FragmentNativeRepository)
50
51     def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
52             mockFragmentRepository, jsonObjectMapper, mockSessionManager, stubFragmentNativeRepository))
53
54     def 'Storing data nodes individually when batch operation fails'(){
55         given: 'two data nodes and supporting repository mock behavior'
56             def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
57             def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
58         and: 'the batch store operation will fail'
59             mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
60         when: 'trying to store data nodes'
61             objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
62         then: 'the two data nodes are saved individually'
63             2 * mockFragmentRepository.save(_);
64     }
65
66     def 'Store single data node.'() {
67         given: 'a data node'
68             def dataNode = new DataNode()
69         when: 'storing a single data node'
70             objectUnderTest.storeDataNode('dataspace1', 'anchor1', dataNode)
71         then: 'the call is redirected to storing a collection of data nodes with just the given data node'
72             1 * objectUnderTest.storeDataNodes('dataspace1', 'anchor1', [dataNode])
73     }
74
75     def 'Handling of StaleStateException (caused by concurrent updates) during update data node and descendants.'() {
76         given: 'the fragment repository returns a fragment entity'
77             mockFragmentRepository.getByDataspaceAndAnchorAndXpath(*_) >> {
78                 def fragmentEntity = new FragmentEntity()
79                 fragmentEntity.setChildFragments([new FragmentEntity()] as Set<FragmentEntity>)
80                 return fragmentEntity
81             }
82         and: 'a data node is concurrently updated by another transaction'
83             mockFragmentRepository.save(_) >> { throw new StaleStateException("concurrent updates") }
84         when: 'attempt to update data node with submitted data nodes'
85             objectUnderTest.updateDataNodeAndDescendants('some-dataspace', 'some-anchor', new DataNodeBuilder().withXpath('/some/xpath').build())
86         then: 'concurrency exception is thrown'
87             def concurrencyException = thrown(ConcurrencyException)
88             assert concurrencyException.getDetails().contains('some-dataspace')
89             assert concurrencyException.getDetails().contains('some-anchor')
90             assert concurrencyException.getDetails().contains('/some/xpath')
91     }
92
93     def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
94         given: 'the system contains and can update one datanode'
95             def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('/node1', 'OK')
96         and: 'the system contains two more datanodes that throw an exception while updating'
97             def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('/node2', 'EXCEPTION')
98             def dataNode3 = createDataNodeAndMockRepositoryMethodSupportingIt('/node3', 'EXCEPTION')
99         and: 'the batch update will therefore also fail'
100             mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
101         when: 'attempt batch update data nodes'
102             objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', [dataNode1, dataNode2, dataNode3])
103         then: 'concurrency exception is thrown'
104             def thrown = thrown(ConcurrencyException)
105             assert thrown.message == 'Concurrent Transactions'
106         and: 'it does not contain the successfull datanode'
107             assert !thrown.details.contains('/node1')
108         and: 'it contains the failed datanodes'
109             assert thrown.details.contains('/node2')
110             assert thrown.details.contains('/node3')
111     }
112
113     def 'Retrieving a data node with a property JSON value of #scenario'() {
114         given: 'the db has a fragment with an attribute property JSON value of #scenario'
115             mockFragmentWithJson("{\"some attribute\": ${dataString}}")
116         when: 'getting the data node represented by this fragment'
117             def dataNode = objectUnderTest.getDataNode('my-dataspace', 'my-anchor',
118                     '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
119         then: 'the leaf is of the correct value and data type'
120             def attributeValue = dataNode.leaves.get('some attribute')
121             assert attributeValue == expectedValue
122             assert attributeValue.class == expectedDataClass
123         where: 'the following Data Type is passed'
124             scenario                              | dataString            || expectedValue     | expectedDataClass
125             'just numbers'                        | '15174'               || 15174             | Integer
126             'number with dot'                     | '15174.32'            || 15174.32          | Double
127             'number with 0 value after dot'       | '15174.0'             || 15174.0           | Double
128             'number with 0 value before dot'      | '0.32'                || 0.32              | Double
129             'number higher than max int'          | '2147483648'          || 2147483648        | Long
130             'just text'                           | '"Test"'              || 'Test'            | String
131             'number with exponent'                | '1.2345e5'            || 1.2345e5          | Double
132             'number higher than max int with dot' | '123456789101112.0'   || 123456789101112.0 | Double
133             'text and numbers'                    | '"String = \'1234\'"' || "String = '1234'" | String
134             'number as String'                    | '"12345"'             || '12345'           | String
135     }
136
137     def 'Retrieving a data node with invalid JSON'() {
138         given: 'a fragment with invalid JSON'
139             mockFragmentWithJson('{invalid json')
140         when: 'getting the data node represented by this fragment'
141             objectUnderTest.getDataNode('my-dataspace', 'my-anchor',
142                     '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
143         then: 'a data validation exception is thrown'
144             thrown(DataValidationException)
145     }
146
147     def 'Retrieving multiple data nodes.'() {
148         given: 'db contains an anchor'
149            def anchorEntity = new AnchorEntity(id:123)
150            mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
151         and: 'fragment repository returns a collection of fragments'
152             def fragmentEntity1 = new FragmentEntity(xpath: '/xpath1', childFragments: [])
153             def fragmentEntity2 = new FragmentEntity(xpath: '/xpath2', childFragments: [])
154             mockFragmentRepository.findByAnchorAndMultipleCpsPaths(123, ['/xpath1', '/xpath2'] as Set<String>) >> [fragmentEntity1, fragmentEntity2]
155         when: 'getting data nodes for 2 xpaths'
156             def result = objectUnderTest.getDataNodes('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
157         then: '2 data nodes are returned'
158             assert result.size() == 2
159     }
160
161     def 'start session'() {
162         when: 'start session'
163             objectUnderTest.startSession()
164         then: 'the session manager method to start session is invoked'
165             1 * mockSessionManager.startSession()
166     }
167
168     def 'close session'() {
169         given: 'session ID'
170             def someSessionId = 'someSessionId'
171         when: 'close session method is called with session ID as parameter'
172             objectUnderTest.closeSession(someSessionId)
173         then: 'the session manager method to close session is invoked with parameter'
174             1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
175     }
176
177     def 'Lock anchor.'(){
178         when: 'lock anchor method is called with anchor entity details'
179             objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
180         then: 'the session manager method to lock anchor is invoked with same parameters'
181             1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
182     }
183
184     def 'update data node leaves: #scenario'(){
185         given: 'A node exists for the given xpath'
186             mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/some/xpath') >> new FragmentEntity(xpath: '/some/xpath', attributes:  existingAttributes)
187         when: 'the node leaves are updated'
188             objectUnderTest.updateDataLeaves('some-dataspace', 'some-anchor', '/some/xpath', newAttributes as Map<String, Serializable>)
189         then: 'the fragment entity saved has the original and new attributes'
190             1 * mockFragmentRepository.save({fragmentEntity -> {
191                 assert fragmentEntity.getXpath() == '/some/xpath'
192                 assert fragmentEntity.getAttributes() == mergedAttributes
193             }})
194         where: 'the following attributes combinations are used'
195             scenario                      | existingAttributes     | newAttributes         | mergedAttributes
196             'add new leaf'                | '{"existing":"value"}' | ["new":"value"]       | '{"existing":"value","new":"value"}'
197             'update existing leaf'        | '{"existing":"value"}' | ["existing":"value2"] | '{"existing":"value2"}'
198             'update nothing with nothing' | ''                     | []                    | ''
199             'update with nothing'         | '{"existing":"value"}' | []                    | '{"existing":"value"}'
200             'update with same value'      | '{"existing":"value"}' | ["existing":"value"]  | '{"existing":"value"}'
201     }
202
203     def 'update data node and descendants: #scenario'(){
204         given: 'mocked responses'
205             mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath') >> new FragmentEntity(xpath: '/test/xpath', childFragments: [])
206         when: 'replace data node tree'
207             objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
208         then: 'call fragment repository save all method'
209             1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
210         where: 'the following Data Type is passed'
211             scenario                         | dataNodes                                                                          || expectedFragmentEntities
212             'empty data node list'           | []                                                                                 || []
213             'one data node in list'          | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'], childDataNodes: [])] || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', childFragments: [])]
214     }
215
216     def 'update data nodes and descendants'() {
217         given: 'the fragment repository returns a fragment entity related to the xpath input'
218             mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath1') >> new FragmentEntity(xpath: '/test/xpath1', childFragments: [])
219             mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/test/xpath2') >> new FragmentEntity(xpath: '/test/xpath2', childFragments: [])
220         and: 'some data nodes with descendants'
221             def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
222             def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
223         when: 'the fragment entities are update by the data nodes'
224             objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', [dataNode1, dataNode2])
225         then: 'call fragment repository save all method is called with the updated fragments'
226             1 * mockFragmentRepository.saveAll({fragmentEntities -> {
227                 fragmentEntities.containsAll([
228                     new FragmentEntity(xpath: '/test/xpath1', attributes: '{"id":"testId1"}', childFragments: [new FragmentEntity(xpath: '/test/xpath1/child', attributes: '{"id":"childTestId1"}', childFragments: [])]),
229                     new FragmentEntity(xpath: '/test/xpath2', attributes: '{"id":"testId2"}', childFragments: [new FragmentEntity(xpath: '/test/xpath2/child', attributes: '{"id":"childTestId2"}', childFragments: [])])
230                 ])
231                 assert fragmentEntities.size() == 2
232             }})
233     }
234
235     def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
236         def dataNode = new DataNodeBuilder().withXpath(xpath).build()
237         def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
238         mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
239         if ('EXCEPTION' == scenario) {
240             mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
241         }
242         return dataNode
243     }
244
245     def mockFragmentWithJson(json) {
246         def anchorEntity = new AnchorEntity(id:123)
247         mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
248         def mockFragmentExtract = Mock(FragmentExtract)
249         mockFragmentExtract.getId() >> 456
250         mockFragmentExtract.getAttributes() >> json
251         mockFragmentRepository.findByAnchorIdAndParentXpath(*_) >> [mockFragmentExtract]
252     }
253
254 }