Improve 32K limit tests
[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-2023 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.DataspaceEntity
28 import org.onap.cps.spi.entities.FragmentEntity
29
30 import org.onap.cps.spi.exceptions.ConcurrencyException
31 import org.onap.cps.spi.exceptions.DataValidationException
32 import org.onap.cps.spi.model.DataNode
33 import org.onap.cps.spi.model.DataNodeBuilder
34 import org.onap.cps.spi.repository.AnchorRepository
35 import org.onap.cps.spi.repository.DataspaceRepository
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 import java.util.stream.Collectors
42
43 class CpsDataPersistenceServiceSpec extends Specification {
44
45     def mockDataspaceRepository = Mock(DataspaceRepository)
46     def mockAnchorRepository = Mock(AnchorRepository)
47     def mockFragmentRepository = Mock(FragmentRepository)
48     def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
49     def mockSessionManager = Mock(SessionManager)
50
51     def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
52             mockFragmentRepository, jsonObjectMapper, mockSessionManager))
53
54     static def anchorEntity = new AnchorEntity(id: 123, dataspace: new DataspaceEntity(id: 1))
55
56     def setup() {
57         mockAnchorRepository.getByDataspaceAndName(_, _) >> anchorEntity
58         mockFragmentRepository.prefetchDescendantsOfFragmentEntities(_, _) >> { fetchDescendantsOption, fragmentEntities -> fragmentEntities }
59     }
60
61     def 'Storing data nodes individually when batch operation fails'(){
62         given: 'two data nodes and supporting repository mock behavior'
63             def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
64             def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
65         and: 'the batch store operation will fail'
66             mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
67         when: 'trying to store data nodes'
68             objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
69         then: 'the two data nodes are saved individually'
70             2 * mockFragmentRepository.save(_)
71     }
72
73     def 'Handling of StaleStateException (caused by concurrent updates) during patch operation for data nodes.'() {
74         given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
75             def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
76                     '/node1': 'OK',
77                     '/node2': 'EXCEPTION',
78                     '/node3': 'EXCEPTION'])
79             def updatedLeavesPerXPath = dataNodes.stream()
80                     .collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves))
81         and: 'the batch update will therefore also fail'
82             mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
83         when: 'attempt batch update data nodes'
84             objectUnderTest.batchUpdateDataLeaves('some-dataspace', 'some-anchor', updatedLeavesPerXPath)
85         then: 'concurrency exception is thrown'
86             def thrown = thrown(ConcurrencyException)
87             assert thrown.message == 'Concurrent Transactions'
88         and: 'it does not contain the successful datanode'
89             assert !thrown.details.contains('/node1')
90         and: 'it contains the failed datanodes'
91             assert thrown.details.contains('/node2')
92             assert thrown.details.contains('/node3')
93     }
94
95     def 'Batch update data node leaves and descendants: #scenario'(){
96         given: 'the fragment repository returns fragment entities related to the xpath inputs'
97             mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
98             mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
99                     new FragmentEntity(1, '/test/xpath', null, "{\"id\":\"testId\"}", anchorEntity, [] as Set)
100             ]
101             mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
102                     new FragmentEntity(1, '/test/xpath1', null, "{\"id\":\"testId1\"}", anchorEntity, [] as Set),
103                     new FragmentEntity(2, '/test/xpath2', null, "{\"id\":\"testId2\"}", anchorEntity, [] as Set)
104             ]
105         when: 'replace data node tree'
106             objectUnderTest.batchUpdateDataLeaves('dataspaceName', 'anchorName',
107                     dataNodes.stream().collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves)))
108         then: 'call fragment repository save all method'
109             1 * mockFragmentRepository.saveAll({fragmentEntities ->
110                 assert fragmentEntities.sort() == expectedFragmentEntities.sort()
111                 assert fragmentEntities.size() == expectedSize
112             })
113         where: 'the following Data Type is passed'
114             scenario                         | dataNodes                                                                                                                              | expectedSize || expectedFragmentEntities
115             'empty data node list'           | []                                                                                                                                     | 0            || []
116             'one data node in list'          | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'])]                                                                         | 1            || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', anchor: anchorEntity)]
117             'multiple data nodes'            | [new DataNode(xpath: '/test/xpath1', leaves: ['id': 'newTestId1']), new DataNode(xpath: '/test/xpath2', leaves: ['id': 'newTestId2'])] | 2            || [new FragmentEntity(xpath: '/test/xpath2', attributes: '{"id":"newTestId2"}', anchor: anchorEntity), new FragmentEntity(xpath: '/test/xpath1', attributes: '{"id":"newTestId1"}', anchor: anchorEntity)]
118     }
119
120     def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
121         given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
122             def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
123                 '/node1': 'OK',
124                 '/node2': 'EXCEPTION',
125                 '/node3': 'EXCEPTION'])
126         and: 'the batch update will therefore also fail'
127             mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
128         when: 'attempt batch update data nodes'
129             objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
130         then: 'concurrency exception is thrown'
131             def thrown = thrown(ConcurrencyException)
132             assert thrown.message == 'Concurrent Transactions'
133         and: 'it does not contain the successful datanode'
134             assert !thrown.details.contains('/node1')
135         and: 'it contains the failed datanodes'
136             assert thrown.details.contains('/node2')
137             assert thrown.details.contains('/node3')
138     }
139
140     def 'Retrieving a data node with a property JSON value of #scenario'() {
141         given: 'the db has a fragment with an attribute property JSON value of #scenario'
142             mockFragmentWithJson("{\"some attribute\": ${dataString}}")
143         when: 'getting the data node represented by this fragment'
144             def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
145                     '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
146         then: 'the leaf is of the correct value and data type'
147             def attributeValue = dataNode[0].leaves.get('some attribute')
148             assert attributeValue == expectedValue
149             assert attributeValue.class == expectedDataClass
150         where: 'the following Data Type is passed'
151             scenario                              | dataString            || expectedValue     | expectedDataClass
152             'just numbers'                        | '15174'               || 15174             | Integer
153             'number with dot'                     | '15174.32'            || 15174.32          | Double
154             'number with 0 value after dot'       | '15174.0'             || 15174.0           | Double
155             'number with 0 value before dot'      | '0.32'                || 0.32              | Double
156             'number higher than max int'          | '2147483648'          || 2147483648        | Long
157             'just text'                           | '"Test"'              || 'Test'            | String
158             'number with exponent'                | '1.2345e5'            || 1.2345e5          | Double
159             'number higher than max int with dot' | '123456789101112.0'   || 123456789101112.0 | Double
160             'text and numbers'                    | '"String = \'1234\'"' || "String = '1234'" | String
161             'number as String'                    | '"12345"'             || '12345'           | String
162     }
163
164     def 'Retrieving a data node with invalid JSON'() {
165         given: 'a fragment with invalid JSON'
166             mockFragmentWithJson('{invalid json')
167         when: 'getting the data node represented by this fragment'
168             objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
169                     '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
170         then: 'a data validation exception is thrown'
171             thrown(DataValidationException)
172     }
173
174     def 'Retrieving multiple data nodes.'() {
175         given: 'fragment repository returns a collection of fragments'
176             mockFragmentRepository.findByAnchorAndXpathIn(anchorEntity, ['/xpath1', '/xpath2'] as Set) >> [
177                 new FragmentEntity(1, '/xpath1', null, null, anchorEntity, [] as Set),
178                 new FragmentEntity(2, '/xpath2', null, null, anchorEntity, [] as Set)
179             ]
180         when: 'getting data nodes for 2 xpaths'
181             def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
182         then: '2 data nodes are returned'
183             assert result.size() == 2
184     }
185
186     def 'start session'() {
187         when: 'start session'
188             objectUnderTest.startSession()
189         then: 'the session manager method to start session is invoked'
190             1 * mockSessionManager.startSession()
191     }
192
193     def 'close session'() {
194         given: 'session ID'
195             def someSessionId = 'someSessionId'
196         when: 'close session method is called with session ID as parameter'
197             objectUnderTest.closeSession(someSessionId)
198         then: 'the session manager method to close session is invoked with parameter'
199             1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
200     }
201
202     def 'Lock anchor.'(){
203         when: 'lock anchor method is called with anchor entity details'
204             objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
205         then: 'the session manager method to lock anchor is invoked with same parameters'
206             1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
207     }
208
209     def 'Replace data node and descendants: #scenario'(){
210         given: 'the fragment repository returns fragment entities related to the xpath inputs'
211             mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
212             mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
213                 new FragmentEntity(1, '/test/xpath', null, '{"id":"testId"}', anchorEntity, [] as Set)
214             ]
215         when: 'replace data node tree'
216             objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
217         then: 'call fragment repository save all method'
218             1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
219         where: 'the following Data Type is passed'
220             scenario                         | dataNodes                                                                          || expectedFragmentEntities
221             'empty data node list'           | []                                                                                 || []
222             '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: [])]
223     }
224
225     def 'Replace data nodes and descendants'() {
226         given: 'the fragment repository returns fragment entities related to the xpath inputs'
227             mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
228                 new FragmentEntity(1, '/test/xpath1', null, null, anchorEntity, [] as Set),
229                 new FragmentEntity(2, '/test/xpath2', null, null, anchorEntity, [] as Set)
230             ]
231         and: 'some data nodes with descendants'
232             def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
233             def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
234         when: 'the fragment entities are update by the data nodes'
235             objectUnderTest.updateDataNodesAndDescendants('dataspace', 'anchor', [dataNode1, dataNode2])
236         then: 'call fragment repository save all method is called with the updated fragments'
237             1 * mockFragmentRepository.saveAll({fragmentEntities -> {
238                 assert fragmentEntities.size() == 2
239                 def fragmentEntityPerXpath = fragmentEntities.collectEntries { [it.xpath, it] }
240                 assert fragmentEntityPerXpath.get('/test/xpath1').childFragments.first().attributes == '{"id":"childTestId1"}'
241                 assert fragmentEntityPerXpath.get('/test/xpath2').childFragments.first().attributes == '{"id":"childTestId2"}'
242             }})
243     }
244
245     def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
246         def dataNode = new DataNodeBuilder().withXpath(xpath).build()
247         def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
248         mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
249         if ('EXCEPTION' == scenario) {
250             mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
251         }
252         return dataNode
253     }
254
255     def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
256         def dataNodes = []
257         def fragmentEntities = []
258         def fragmentId = 1
259         xpathToScenarioMap.each {
260             def xpath = it.key
261             def scenario = it.value
262             def dataNode = new DataNodeBuilder().withXpath(xpath).build()
263             dataNodes.add(dataNode)
264             def fragmentEntity = new FragmentEntity(id: fragmentId, anchor: anchorEntity, xpath: xpath, childFragments: [])
265             fragmentEntities.add(fragmentEntity)
266             if ('EXCEPTION' == scenario) {
267                 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
268             }
269             fragmentId++
270         }
271         mockFragmentRepository.findByAnchorAndXpathIn(_, xpathToScenarioMap.keySet()) >> fragmentEntities
272         return dataNodes
273     }
274
275     def mockFragmentWithJson(json) {
276         def fragmentEntity = new FragmentEntity(456, '/parent-01', null, json, anchorEntity, [] as Set)
277         mockFragmentRepository.findByAnchorAndXpathIn(_, ['/parent-01'] as Set) >> [fragmentEntity]
278     }
279
280 }