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