Performance Improvement: Fix Insert Yang Resource IDs (Schemset)
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsModulePersistenceServiceIntegrationSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 Nordix Foundation
4  *  Modifications Copyright (C) 2021-2022 Bell Canada.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the 'License');
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an 'AS IS' BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21 package org.onap.cps.spi.impl
22
23 import org.onap.cps.spi.CpsAdminPersistenceService
24 import org.onap.cps.spi.CpsModulePersistenceService
25 import org.onap.cps.spi.entities.YangResourceEntity
26 import org.onap.cps.spi.exceptions.AlreadyDefinedException
27 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
28 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
29 import org.onap.cps.spi.model.ModuleDefinition
30 import org.onap.cps.spi.model.ModuleReference
31 import org.onap.cps.spi.repository.AnchorRepository
32 import org.onap.cps.spi.repository.SchemaSetRepository
33 import org.onap.cps.spi.repository.SchemaSetYangResourceRepositoryImpl
34 import org.onap.cps.spi.repository.YangResourceRepository
35 import org.springframework.beans.factory.annotation.Autowired
36 import org.springframework.test.context.jdbc.Sql
37 import spock.lang.Ignore
38
39 class CpsModulePersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
40
41     @Autowired
42     CpsModulePersistenceService objectUnderTest
43
44     @Autowired
45     AnchorRepository anchorRepository
46
47     @Autowired
48     SchemaSetRepository schemaSetRepository
49
50     @Autowired
51     CpsAdminPersistenceService cpsAdminPersistenceService
52
53     @Autowired
54     YangResourceRepository yangResourceRepository
55
56     final static String SET_DATA = '/data/schemaset.sql'
57
58     def static EXISTING_SCHEMA_SET_NAME = SCHEMA_SET_NAME1
59     def SCHEMA_SET_NAME_NO_ANCHORS = 'SCHEMA-SET-100'
60     def NEW_SCHEMA_SET_NAME = 'SCHEMA-SET-NEW'
61     def NEW_RESOURCE_NAME = 'some new resource'
62     def NEW_RESOURCE_CONTENT = 'module stores {\n' +
63             '    yang-version 1.1;\n' +
64             '    namespace "org:onap:ccsdk:sample";\n' +
65             '\n' +
66             '    prefix book-store;\n' +
67             '\n' +
68             '    revision "2020-09-15" {\n' +
69             '        description\n' +
70             '        "Sample Model";\n' +
71             '    }' +
72             '}'
73     def NEW_RESOURCE_CHECKSUM = 'b13faef573ed1374139d02c40d8ce09c80ea1dc70e63e464c1ed61568d48d539'
74     def NEW_RESOURCE_MODULE_NAME = 'stores'
75     def NEW_RESOURCE_REVISION = '2020-09-15'
76     def newYangResourcesNameToContentMap = [(NEW_RESOURCE_NAME):NEW_RESOURCE_CONTENT]
77
78     def dataspaceEntity
79
80     def setup() {
81         dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
82     }
83
84     @Sql([CLEAR_DATA, SET_DATA])
85     def 'Getting yang resource ids from module references'() {
86         when: 'getting yang resources for #scenario'
87             def result = yangResourceRepository.getResourceIdsByModuleReferences(moduleReferences)
88         then: 'the result contains the expected number entries'
89             assert result.size() == expectedResultSize
90         where: 'the following module references are provided'
91             scenario                                 | moduleReferences                                                                                                 || expectedResultSize
92             '2 valid module references'              | [ new ModuleReference('MODULE-NAME-002','REVISION-002'), new ModuleReference('MODULE-NAME-003','REVISION-002') ] || 2
93             '1 invalid module reference'             | [ new ModuleReference('NOT EXIST','IRRELEVANT') ]                                                                || 0
94             '1 valid and 1 invalid module reference' | [ new ModuleReference('MODULE-NAME-002','REVISION-002'), new ModuleReference('NOT EXIST','IRRELEVANT') ]         || 1
95             'no module references'                   | []                                                                                                               || 0
96     }
97
98     @Sql([CLEAR_DATA, SET_DATA])
99     def 'Store schema set error scenario: #scenario.'() {
100         when: 'attempt to store schema set #schemaSetName in dataspace #dataspaceName'
101             objectUnderTest.storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesNameToContentMap)
102         then: 'an #expectedException is thrown'
103             thrown(expectedException)
104         where: 'the following data is used'
105             scenario                    | dataspaceName  | schemaSetName            || expectedException
106             'dataspace does not exist'  | 'unknown'      | 'not-relevant'           || DataspaceNotFoundException
107             'schema set already exists' | DATASPACE_NAME | EXISTING_SCHEMA_SET_NAME || AlreadyDefinedException
108     }
109
110     @Sql([CLEAR_DATA, SET_DATA])
111     def 'Store new schema set with one module'() {
112         when: 'a new schema set with one module is stored'
113             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
114         then: 'the schema set is persisted correctly'
115            assertSchemaSetWithOneModuleIsPersistedCorrectly(NEW_RESOURCE_NAME,
116                NEW_RESOURCE_MODULE_NAME, NEW_RESOURCE_REVISION, NEW_RESOURCE_CONTENT, NEW_RESOURCE_CHECKSUM)
117     }
118
119     @Sql([CLEAR_DATA, SET_DATA])
120     def 'Store new schema set with multiple modules.'() {
121         given: 'a new schema set with #numberOfModules modules'
122             def numberOfModules =  2
123             String schemaSetName = "NewSchemaWith${numberOfModules}Modules"
124             def newYangResourcesNameToContentMap = [:]
125             (1..numberOfModules).each {
126                 def uniqueRevision = String.valueOf(2000 + it) + '-01-01'
127                 def uniqueContent = NEW_RESOURCE_CONTENT.replace(NEW_RESOURCE_REVISION, uniqueRevision)
128                 newYangResourcesNameToContentMap.put(uniqueRevision, uniqueContent)
129             }
130         when: 'the new schema set is stored'
131             objectUnderTest.storeSchemaSet(DATASPACE_NAME, schemaSetName, newYangResourcesNameToContentMap)
132         then: 'the correct number of modules are persisted'
133             assert getYangResourceEntities(schemaSetName).size() == numberOfModules
134     }
135
136     @Sql([CLEAR_DATA, SET_DATA])
137     def 'Store and retrieve new schema set from new modules and existing modules.'() {
138         given: 'a new module'
139             def mapOfNewModules = [newModule: 'module newmodule { yang-version 1.1; revision "2022-08-19" { } }']
140         and: 'there are more existing modules in the db than the batch size (100)'
141             def listOfExistingModulesModuleReference = []
142             def mapOfExistingModule = [:]
143             def numberOfModules =  1 + SchemaSetYangResourceRepositoryImpl.MAX_INSERT_BATCH_SIZE
144             (1..numberOfModules).each {
145                 def uniqueRevision = String.valueOf(2000 + it) + '-01-01'
146                 def uniqueContent = "module test { yang-version 1.1; revision \"${uniqueRevision}\" { } }".toString()
147                 mapOfNewModules.put( 'test' + it, uniqueContent)
148                 listOfExistingModulesModuleReference.add(new ModuleReference('test',uniqueRevision))
149             }
150             objectUnderTest.storeSchemaSet(DATASPACE_NAME, 'existing schema set ', mapOfExistingModule)
151         when: 'a new schema set is created from these new modules and existing modules'
152             objectUnderTest.storeSchemaSetFromModules(DATASPACE_NAME, NEW_SCHEMA_SET_NAME , mapOfNewModules, listOfExistingModulesModuleReference)
153         then: 'the schema set can be retrieved'
154             def actualYangResourcesMapAfterSchemaSetHasBeenCreated =
155                     objectUnderTest.getYangSchemaResources(DATASPACE_NAME, NEW_SCHEMA_SET_NAME)
156         and: 'it has all the new and existing modules'
157             def expectedYangResourcesMapAfterSchemaSetHasBeenCreated = mapOfNewModules + mapOfExistingModule
158             assert actualYangResourcesMapAfterSchemaSetHasBeenCreated == expectedYangResourcesMapAfterSchemaSetHasBeenCreated
159     }
160
161     @Sql([CLEAR_DATA, SET_DATA])
162     def 'Retrieving schema set (resources) by anchor.'() {
163         given: 'a new schema set is stored'
164             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
165         and: 'an anchor is created with that schema set'
166             cpsAdminPersistenceService.createAnchor(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, ANCHOR_NAME1)
167         when: 'the schema set resources for that anchor is retrieved'
168             def result = objectUnderTest.getYangSchemaSetResources(DATASPACE_NAME, ANCHOR_NAME1)
169         then: 'the correct resources are returned'
170              result == newYangResourcesNameToContentMap
171     }
172
173     @Sql([CLEAR_DATA, SET_DATA])
174     def 'Retrieving all yang resources module references for the given dataspace.'() {
175         given: 'a dataspace name'
176             def dataspaceName = 'DATASPACE-002'
177         when: 'all yang resources module references are retrieved for the given dataspace name'
178             def result = objectUnderTest.getYangResourceModuleReferences(dataspaceName)
179         then: 'the correct resources are returned'
180             result.sort() == [new ModuleReference(moduleName: 'MODULE-NAME-005', revision: 'REVISION-002'),
181                               new ModuleReference(moduleName: 'MODULE-NAME-006', revision: 'REVISION-006')]
182     }
183
184     @Sql([CLEAR_DATA, SET_DATA])
185     def 'Retrieving module names and revisions for the given anchor.'() {
186         given: 'a dataspace name and anchor name'
187             def dataspaceName = 'DATASPACE-001'
188             def anchorName = 'ANCHOR1'
189         when: 'all yang resources module references are retrieved for the given anchor'
190             def result = objectUnderTest.getYangResourceModuleReferences(dataspaceName, anchorName)
191         then: 'the correct module names and revisions are returned'
192             result.sort() == [ new ModuleReference(moduleName: 'MODULE-NAME-003', revision: 'REVISION-002'),
193                               new ModuleReference(moduleName: 'MODULE-NAME-004', revision: 'REVISION-004')]
194     }
195
196     @Sql([CLEAR_DATA, SET_DATA])
197     def 'Storing duplicate schema content.'() {
198         given: 'a new schema set with a resource with the same content as an existing resource'
199             def existingResourceContent = 'module test { yang-version 1.1; revision "2020-09-15"; }'
200             def newYangResourcesNameToContentMap = [(NEW_RESOURCE_NAME):existingResourceContent]
201         when: 'the schema set with duplicate resource is stored'
202             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
203         then: 'the schema persisted has the new name and has the same checksum'
204             def existingResourceChecksum = 'bea1afcc3d1517e7bf8cae151b3b6bfbd46db77a81754acdcb776a50368efa0a'
205             def existingResourceModuleName = 'test'
206             def existingResourceRevision = '2020-09-15'
207             assertSchemaSetWithOneModuleIsPersistedCorrectly(NEW_RESOURCE_NAME, existingResourceModuleName,
208                 existingResourceRevision, existingResourceContent, existingResourceChecksum)
209     }
210
211     @Sql([CLEAR_DATA, SET_DATA])
212     def 'Delete schema set'() {
213         when: 'a schema set is deleted with cascade-prohibited option'
214             objectUnderTest.deleteSchemaSet(DATASPACE_NAME, SCHEMA_SET_NAME_NO_ANCHORS)
215         then: 'the schema set has been deleted'
216             schemaSetRepository.findByDataspaceAndName(dataspaceEntity, SCHEMA_SET_NAME_NO_ANCHORS).isPresent() == false
217     }
218
219     @Sql([CLEAR_DATA, SET_DATA])
220     def 'Identifying new module references where #scenario'() {
221         when: 'identifyNewModuleReferences is called'
222             def result = objectUnderTest.identifyNewModuleReferences(moduleReferences)
223         then: 'the correct module reference collection is returned'
224             assert result == expectedResult
225         where: 'the following data is used'
226             scenario                              | moduleReferences                                                                                  || expectedResult
227             'new module references exist'         | toModuleReference([['some module 1' : 'some revision 1'], ['some module 2' : 'some revision 2']]) || toModuleReference([['some module 1' : 'some revision 1'], ['some module 2' : 'some revision 2']])
228             'no new module references exist'      | []                                                                                                || []
229             'module references collection is null'| null                                                                                              || []
230     }
231
232     @Sql([CLEAR_DATA, SET_DATA])
233     def 'Delete schema set error scenario: #scenario.'() {
234         when: 'attempt to delete a schema set where #scenario'
235             objectUnderTest.deleteSchemaSet(dataspaceName, schemaSetName)
236         then: 'an #expectedException is thrown'
237             thrown(expectedException)
238         where: 'the following data is used'
239             scenario                                   | dataspaceName  | schemaSetName                         || expectedException
240             'dataspace does not exist'                 | 'unknown'      | 'not-relevant'                        || DataspaceNotFoundException
241             'schema set does not exists'               | DATASPACE_NAME | 'unknown'                             || SchemaSetNotFoundException
242     }
243
244     @Sql([CLEAR_DATA, SET_DATA])
245     def 'Delete only orphan Yang Resources'() {
246         given: 'a schema set is deleted and and yang resource is not used anymore'
247             objectUnderTest.deleteSchemaSet(DATASPACE_NAME, SCHEMA_SET_NAME_NO_ANCHORS)
248         when: 'orphan yang resources are deleted'
249             objectUnderTest.deleteUnusedYangResourceModules()
250         then: 'any orphaned (not used by any schema set anymore) yang resources are deleted'
251             def orphanedResourceId = 3100L
252             yangResourceRepository.findById(orphanedResourceId).isPresent() == false
253         and: 'any shared (still in use by other schema set) yang resources still persists'
254             def sharedResourceId = 3003L
255             yangResourceRepository.findById(sharedResourceId).isPresent()
256     }
257
258     @Sql([CLEAR_DATA, SET_DATA])
259     def 'Retrieving all yang resources module definition for the given dataspace and anchor name.'() {
260         when: 'all yang resources module definitions are retrieved for the given dataspace and anchor name'
261             def result = objectUnderTest.getYangResourceDefinitions('DATASPACE-001', 'ANCHOR3')
262         then: 'the correct module definitions (moduleName, revision and yang resource content) are returned'
263             result.sort() == [new ModuleDefinition('MODULE-NAME-004', 'REVISION-004', 'CONTENT-004')]
264     }
265
266     def assertSchemaSetWithOneModuleIsPersistedCorrectly(expectedYangResourceName,
267                                                          expectedYangResourceModuleName,
268                                                          expectedYangResourceRevision,
269                                                          expectedYangResourceContent,
270                                                          expectedYangResourceChecksum) {
271
272         // assert the attached yang resource is persisted
273         def yangResourceEntities = getYangResourceEntities(NEW_SCHEMA_SET_NAME)
274         assert yangResourceEntities.size() == 1
275
276         // assert the attached yang resource content
277         YangResourceEntity yangResourceEntity = yangResourceEntities.iterator().next()
278         assert yangResourceEntity.id != null
279         assert yangResourceEntity.fileName == expectedYangResourceName
280         assert yangResourceEntity.moduleName == expectedYangResourceModuleName
281         assert yangResourceEntity.revision == expectedYangResourceRevision
282         assert yangResourceEntity.content == expectedYangResourceContent
283         assert yangResourceEntity.checksum == expectedYangResourceChecksum
284         return true
285     }
286
287     def getYangResourceEntities(schemaSetName) {
288         def schemaSetEntity = schemaSetRepository
289             .findByDataspaceAndName(dataspaceEntity, schemaSetName).orElseThrow()
290         return schemaSetEntity.getYangResources()
291     }
292
293     def toModuleReference(moduleReferenceAsMap) {
294         def moduleReferences = [].withDefault { [:] }
295         moduleReferenceAsMap.forEach(property ->
296             property.forEach((moduleName, revision) -> {
297                 moduleReferences.add(new ModuleReference('moduleName' : moduleName, 'revision' : revision))
298             }))
299         return moduleReferences
300     }
301
302 }