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