eac28873e79684d2ebf7a5650811e5fa0f9383fc
[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.springframework.beans.factory.annotation.Autowired
35 import org.springframework.test.context.jdbc.Sql
36
37 class CpsModulePersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
38
39     @Autowired
40     CpsModulePersistenceService objectUnderTest
41
42     @Autowired
43     AnchorRepository anchorRepository
44
45     @Autowired
46     SchemaSetRepository schemaSetRepository
47
48     @Autowired
49     CpsAdminPersistenceService cpsAdminPersistenceService
50
51     final static String SET_DATA = '/data/schemaset.sql'
52
53     def static EXISTING_SCHEMA_SET_NAME = SCHEMA_SET_NAME1
54     def SCHEMA_SET_NAME_NO_ANCHORS = 'SCHEMA-SET-100'
55     def NEW_SCHEMA_SET_NAME = 'SCHEMA-SET-NEW'
56     def NEW_RESOURCE_NAME = 'some new resource'
57     def NEW_RESOURCE_CONTENT = 'module stores {\n' +
58             '    yang-version 1.1;\n' +
59             '    namespace "org:onap:ccsdk:sample";\n' +
60             '\n' +
61             '    prefix book-store;\n' +
62             '\n' +
63             '    revision "2020-09-15" {\n' +
64             '        description\n' +
65             '        "Sample Model";\n' +
66             '    }' +
67             '}'
68     def NEW_RESOURCE_CHECKSUM = 'b13faef573ed1374139d02c40d8ce09c80ea1dc70e63e464c1ed61568d48d539'
69     def NEW_RESOURCE_MODULE_NAME = 'stores'
70     def NEW_RESOURCE_REVISION = '2020-09-15'
71     def newYangResourcesNameToContentMap = [(NEW_RESOURCE_NAME):NEW_RESOURCE_CONTENT]
72
73     def dataspaceEntity
74
75     def setup() {
76         dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
77     }
78
79     @Sql([CLEAR_DATA, SET_DATA])
80     def 'Store schema set error scenario: #scenario.'() {
81         when: 'attempt to store schema set #schemaSetName in dataspace #dataspaceName'
82             objectUnderTest.storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesNameToContentMap)
83         then: 'an #expectedException is thrown'
84             thrown(expectedException)
85         where: 'the following data is used'
86             scenario                    | dataspaceName  | schemaSetName            || expectedException
87             'dataspace does not exist'  | 'unknown'      | 'not-relevant'           || DataspaceNotFoundException
88             'schema set already exists' | DATASPACE_NAME | EXISTING_SCHEMA_SET_NAME || AlreadyDefinedException
89     }
90
91     @Sql([CLEAR_DATA, SET_DATA])
92     def 'Store new schema set with one module'() {
93         when: 'a new schema set with one module is stored'
94             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
95         then: 'the schema set is persisted correctly'
96            assertSchemaSetWithOneModuleIsPersistedCorrectly(NEW_RESOURCE_NAME,
97                NEW_RESOURCE_MODULE_NAME, NEW_RESOURCE_REVISION, NEW_RESOURCE_CONTENT, NEW_RESOURCE_CHECKSUM)
98     }
99
100     @Sql([CLEAR_DATA, SET_DATA])
101     def 'Store new schema set with multiple modules.'() {
102         given: 'a new schema set with #numberOfModules modules'
103             def numberOfModules =  2
104             String schemaSetName = "NewSchemaWith${numberOfModules}Modules"
105             def newYangResourcesNameToContentMap = [:]
106             (1..numberOfModules).each {
107                 def uniqueRevision = String.valueOf(2000 + it) + '-01-01'
108                 def uniqueContent = NEW_RESOURCE_CONTENT.replace(NEW_RESOURCE_REVISION, uniqueRevision)
109                 newYangResourcesNameToContentMap.put(uniqueRevision, uniqueContent)
110             }
111         when: 'the new schema set is stored'
112             objectUnderTest.storeSchemaSet(DATASPACE_NAME, schemaSetName, newYangResourcesNameToContentMap)
113         then: 'the correct number of modules are persisted'
114             assert getYangResourceEntities(schemaSetName).size() == numberOfModules
115     }
116
117     @Sql([CLEAR_DATA, SET_DATA])
118     def 'Store and retrieve new schema set from new modules and existing modules.'() {
119         given: 'a new module'
120             def mapOfNewModules = [newModule: 'module newmodule { yang-version 1.1; revision "2022-08-19" { } }']
121         and: 'there are more existing modules in the db than the batch size (100)'
122             def listOfExistingModulesModuleReference = []
123             def mapOfExistingModule = [:]
124             def numberOfModules =  1 + SchemaSetYangResourceRepositoryImpl.MAX_INSERT_BATCH_SIZE
125             (1..numberOfModules).each {
126                 def uniqueRevision = String.valueOf(2000 + it) + '-01-01'
127                 def uniqueContent = "module test { yang-version 1.1; revision \"${uniqueRevision}\" { } }".toString()
128                 mapOfNewModules.put( 'test' + it, uniqueContent)
129                 listOfExistingModulesModuleReference.add(new ModuleReference('test',uniqueRevision))
130             }
131             objectUnderTest.storeSchemaSet(DATASPACE_NAME, 'existing schema set ', mapOfExistingModule)
132         when: 'a new schema set is created from these new modules and existing modules'
133             objectUnderTest.storeSchemaSetFromModules(DATASPACE_NAME, NEW_SCHEMA_SET_NAME , mapOfNewModules, listOfExistingModulesModuleReference)
134         then: 'the schema set can be retrieved'
135             def actualYangResourcesMapAfterSchemaSetHasBeenCreated =
136                     objectUnderTest.getYangSchemaResources(DATASPACE_NAME, NEW_SCHEMA_SET_NAME)
137         and: 'it has all the new and existing modules'
138             def expectedYangResourcesMapAfterSchemaSetHasBeenCreated = mapOfNewModules + mapOfExistingModule
139             assert actualYangResourcesMapAfterSchemaSetHasBeenCreated == expectedYangResourcesMapAfterSchemaSetHasBeenCreated
140     }
141
142     @Sql([CLEAR_DATA, SET_DATA])
143     def 'Retrieving schema set (resources) by anchor.'() {
144         given: 'a new schema set is stored'
145             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
146         and: 'an anchor is created with that schema set'
147             cpsAdminPersistenceService.createAnchor(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, ANCHOR_NAME1)
148         when: 'the schema set resources for that anchor is retrieved'
149             def result = objectUnderTest.getYangSchemaSetResources(DATASPACE_NAME, ANCHOR_NAME1)
150         then: 'the correct resources are returned'
151              result == newYangResourcesNameToContentMap
152     }
153
154     @Sql([CLEAR_DATA, SET_DATA])
155     def 'Retrieving all yang resources module references for the given dataspace.'() {
156         given: 'a dataspace name'
157             def dataspaceName = 'DATASPACE-002'
158         when: 'all yang resources module references are retrieved for the given dataspace name'
159             def result = objectUnderTest.getYangResourceModuleReferences(dataspaceName)
160         then: 'the correct resources are returned'
161             result.sort() == [new ModuleReference(moduleName: 'MODULE-NAME-005', revision: 'REVISION-002'),
162                               new ModuleReference(moduleName: 'MODULE-NAME-006', revision: 'REVISION-006')]
163     }
164
165     @Sql([CLEAR_DATA, SET_DATA])
166     def 'Retrieving module names and revisions for the given anchor.'() {
167         given: 'a dataspace name and anchor name'
168             def dataspaceName = 'DATASPACE-001'
169             def anchorName = 'ANCHOR1'
170         when: 'all yang resources module references are retrieved for the given anchor'
171             def result = objectUnderTest.getYangResourceModuleReferences(dataspaceName, anchorName)
172         then: 'the correct module names and revisions are returned'
173             result.sort() == [ new ModuleReference(moduleName: 'MODULE-NAME-003', revision: 'REVISION-002'),
174                               new ModuleReference(moduleName: 'MODULE-NAME-004', revision: 'REVISION-004')]
175     }
176
177     @Sql([CLEAR_DATA, SET_DATA])
178     def 'Storing duplicate schema content.'() {
179         given: 'a new schema set with a resource with the same content as an existing resource'
180             def existingResourceContent = 'module test { yang-version 1.1; revision "2020-09-15"; }'
181             def newYangResourcesNameToContentMap = [(NEW_RESOURCE_NAME):existingResourceContent]
182         when: 'the schema set with duplicate resource is stored'
183             objectUnderTest.storeSchemaSet(DATASPACE_NAME, NEW_SCHEMA_SET_NAME, newYangResourcesNameToContentMap)
184         then: 'the schema persisted has the new name and has the same checksum'
185             def existingResourceChecksum = 'bea1afcc3d1517e7bf8cae151b3b6bfbd46db77a81754acdcb776a50368efa0a'
186             def existingResourceModuleName = 'test'
187             def existingResourceRevision = '2020-09-15'
188             assertSchemaSetWithOneModuleIsPersistedCorrectly(NEW_RESOURCE_NAME, existingResourceModuleName,
189                 existingResourceRevision, existingResourceContent, existingResourceChecksum)
190     }
191
192     @Sql([CLEAR_DATA, SET_DATA])
193     def 'Delete schema set'() {
194         when: 'a schema set is deleted with cascade-prohibited option'
195             objectUnderTest.deleteSchemaSet(DATASPACE_NAME, SCHEMA_SET_NAME_NO_ANCHORS)
196         then: 'the schema set has been deleted'
197             schemaSetRepository.findByDataspaceAndName(dataspaceEntity, SCHEMA_SET_NAME_NO_ANCHORS).isPresent() == false
198     }
199
200     @Sql([CLEAR_DATA, SET_DATA])
201     def 'Identifying new module references where #scenario'() {
202         when: 'identifyNewModuleReferences is called'
203             def result = objectUnderTest.identifyNewModuleReferences(moduleReferences)
204         then: 'the correct module reference collection is returned'
205             assert result == expectedResult
206         where: 'the following data is used'
207             scenario                              | moduleReferences                                                                                  || expectedResult
208             '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']])
209             'no new module references exist'      | []                                                                                                || []
210             'module references collection is null'| null                                                                                              || []
211     }
212
213     @Sql([CLEAR_DATA, SET_DATA])
214     def 'Delete schema set error scenario: #scenario.'() {
215         when: 'attempt to delete a schema set where #scenario'
216             objectUnderTest.deleteSchemaSet(dataspaceName, schemaSetName)
217         then: 'an #expectedException is thrown'
218             thrown(expectedException)
219         where: 'the following data is used'
220             scenario                                   | dataspaceName  | schemaSetName                         || expectedException
221             'dataspace does not exist'                 | 'unknown'      | 'not-relevant'                        || DataspaceNotFoundException
222             'schema set does not exists'               | DATASPACE_NAME | 'unknown'                             || SchemaSetNotFoundException
223     }
224
225     @Sql([CLEAR_DATA, SET_DATA])
226     def 'Delete only orphan Yang Resources'() {
227         given: 'a schema set is deleted and and yang resource is not used anymore'
228             objectUnderTest.deleteSchemaSet(DATASPACE_NAME, SCHEMA_SET_NAME_NO_ANCHORS)
229         when: 'orphan yang resources are deleted'
230             objectUnderTest.deleteUnusedYangResourceModules()
231         then: 'any orphaned (not used by any schema set anymore) yang resources are deleted'
232             def orphanedResourceId = 3100L
233             yangResourceRepository.findById(orphanedResourceId).isPresent() == false
234         and: 'any shared (still in use by other schema set) yang resources still persists'
235             def sharedResourceId = 3003L
236             yangResourceRepository.findById(sharedResourceId).isPresent()
237     }
238
239     @Sql([CLEAR_DATA, SET_DATA])
240     def 'Retrieving all yang resources module definition for the given dataspace and anchor name.'() {
241         when: 'all yang resources module definitions are retrieved for the given dataspace and anchor name'
242             def result = objectUnderTest.getYangResourceDefinitions('DATASPACE-001', 'ANCHOR3')
243         then: 'the correct module definitions (moduleName, revision and yang resource content) are returned'
244             result.sort() == [new ModuleDefinition('MODULE-NAME-004', 'REVISION-004', 'CONTENT-004')]
245     }
246
247     def assertSchemaSetWithOneModuleIsPersistedCorrectly(expectedYangResourceName,
248                                                          expectedYangResourceModuleName,
249                                                          expectedYangResourceRevision,
250                                                          expectedYangResourceContent,
251                                                          expectedYangResourceChecksum) {
252
253         // assert the attached yang resource is persisted
254         def yangResourceEntities = getYangResourceEntities(NEW_SCHEMA_SET_NAME)
255         assert yangResourceEntities.size() == 1
256
257         // assert the attached yang resource content
258         YangResourceEntity yangResourceEntity = yangResourceEntities.iterator().next()
259         assert yangResourceEntity.id != null
260         assert yangResourceEntity.fileName == expectedYangResourceName
261         assert yangResourceEntity.moduleName == expectedYangResourceModuleName
262         assert yangResourceEntity.revision == expectedYangResourceRevision
263         assert yangResourceEntity.content == expectedYangResourceContent
264         assert yangResourceEntity.checksum == expectedYangResourceChecksum
265         return true
266     }
267
268     def getYangResourceEntities(schemaSetName) {
269         def schemaSetEntity = schemaSetRepository
270             .findByDataspaceAndName(dataspaceEntity, schemaSetName).orElseThrow()
271         return schemaSetEntity.getYangResources()
272     }
273
274     def toModuleReference(moduleReferenceAsMap) {
275         def moduleReferences = [].withDefault { [:] }
276         moduleReferenceAsMap.forEach(property ->
277             property.forEach((moduleName, revision) -> {
278                 moduleReferences.add(new ModuleReference('moduleName' : moduleName, 'revision' : revision))
279             }))
280         return moduleReferences
281     }
282
283 }