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