5384f31cc1dc6ae34b42d5613c66372813ec7ed2
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / inventory / sync / ModuleSyncServiceSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl.inventory.sync
22
23 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME
24 import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_UPGRADE
25
26 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState
27 import org.onap.cps.spi.FetchDescendantsOption
28 import org.onap.cps.spi.model.DataNode
29 import org.onap.cps.api.CpsAdminService
30 import org.onap.cps.api.CpsDataService
31 import org.onap.cps.api.CpsModuleService
32 import org.onap.cps.spi.model.DataNodeBuilder
33 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations
34 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
35 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries
36 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder
37 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
38 import org.onap.cps.spi.CascadeDeleteAllowed
39 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
40 import org.onap.cps.spi.model.ModuleReference
41 import org.onap.cps.utils.JsonObjectMapper
42 import spock.lang.Specification
43
44 class ModuleSyncServiceSpec extends Specification {
45
46     def mockCpsModuleService = Mock(CpsModuleService)
47     def mockDmiModelOperations = Mock(DmiModelOperations)
48     def mockCpsAdminService = Mock(CpsAdminService)
49     def mockCmHandleQueries = Mock(CmHandleQueries)
50     def mockCpsDataService = Mock(CpsDataService)
51     def mockJsonObjectMapper = Mock(JsonObjectMapper)
52     def mockModuleSetTagCache = [:]
53
54     def objectUnderTest = new ModuleSyncService(mockDmiModelOperations, mockCpsModuleService, mockCpsAdminService,
55             mockCmHandleQueries, mockCpsDataService, mockJsonObjectMapper, mockModuleSetTagCache)
56
57     def expectedDataspaceName = NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME
58     def static cmHandleWithModuleSetTag = new DataNodeBuilder().withXpath("//cm-handles[@module-set-tag='tag-1'][@id='otherId']").withAnchor('otherId').build()
59
60     def 'Sync model for a NEW cm handle without cache with #scenario'() {
61         given: 'a cm handle having some state'
62             def ncmpServiceCmHandle = new NcmpServiceCmHandle()
63             ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.ADVISED).build())
64             ncmpServiceCmHandle.cmHandleId = 'ch-1'
65             def yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle('some service name', '', '', ncmpServiceCmHandle, moduleSetTag)
66         and: 'DMI operations returns some module references'
67             def moduleReferences =  [ new ModuleReference('module1','1'), new ModuleReference('module2','2') ]
68             mockDmiModelOperations.getModuleReferences(yangModelCmHandle) >> moduleReferences
69         and: 'DMI-Plugin returns resource(s) for "new" module(s)'
70             mockDmiModelOperations.getNewYangResourcesFromDmi(yangModelCmHandle, [new ModuleReference('module1', '1')]) >> newModuleNameContentToMap
71         and: 'the module service identifies #identifiedNewModuleReferences.size() new modules'
72             mockCpsModuleService.identifyNewModuleReferences(moduleReferences) >> toModuleReferences(identifiedNewModuleReferences)
73         and: 'system contains #existingCmHandlesWithSameTag.size() cm handles with same tag'
74             mockCmHandleQueries.queryNcmpRegistryByCpsPath("//cm-handles[@module-set-tag='new-tag-1']",
75                     FetchDescendantsOption.OMIT_DESCENDANTS) >> []
76         when: 'module sync is triggered'
77             objectUnderTest.syncAndCreateOrUpgradeSchemaSetAndAnchor(yangModelCmHandle)
78         then: 'create schema set from module is invoked with correct parameters'
79             1 * mockCpsModuleService.createOrUpgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'ch-1', newModuleNameContentToMap, moduleReferences)
80         and: 'anchor is created with the correct parameters'
81             1 * mockCpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'ch-1', 'ch-1')
82         where: 'the following parameters are used'
83             scenario         | existingModuleResourcesInCps         | identifiedNewModuleReferences | newModuleNameContentToMap     | moduleSetTag
84             'one new module' | [['module2': '2'], ['module3': '3']] | [['module1': '1']]            | [module1: 'some yang source'] | ''
85             'no new module'  | [['module1': '1'], ['module2': '2']] | []                            | [:]                           | 'new-tag-1'
86     }
87
88     def 'Upgrade model for an existing cm handle with Module Set Tag where the modules are #scenario'() {
89         given: 'a cm handle being upgraded to module set tag: tag-1'
90             def ncmpServiceCmHandle = new NcmpServiceCmHandle()
91             ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withLockReason(MODULE_UPGRADE, 'Upgrade to ModuleSetTag: tag-1').build())
92             def dmiServiceName = 'some service name'
93             ncmpServiceCmHandle.cmHandleId = 'upgraded-ch'
94             def yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(dmiServiceName, '', '', ncmpServiceCmHandle,'tag-1')
95         and: 'some module references'
96             def moduleReferences =  [ new ModuleReference('module1','1') ]
97         and: 'cache or DMI operations returns some module references for upgraded cm handle'
98             if (populateCache) {
99                 mockModuleSetTagCache.put('tag-1', moduleReferences)
100             } else {
101                 mockDmiModelOperations.getModuleReferences(yangModelCmHandle) >> moduleReferences
102             }
103         and: 'none of these module references are new (unknown to the system)'
104             mockCpsModuleService.identifyNewModuleReferences(moduleReferences) >> []
105         and: 'CPS-Core returns list of existing module resources for TBD'
106             mockCpsModuleService.getYangResourcesModuleReferences(*_) >> [ new ModuleReference('module1','1') ]
107         and: 'system contains #existingCmHandlesWithSameTag.size() cm handles with same tag'
108             mockCmHandleQueries.queryNcmpRegistryByCpsPath("//cm-handles[@module-set-tag='tag-1']", FetchDescendantsOption.OMIT_DESCENDANTS) >> existingCmHandlesWithSameTag
109         and: 'the other cm handle is a state ready'
110             mockCmHandleQueries.cmHandleHasState('otherId', CmHandleState.READY) >> true
111         when: 'module sync is triggered'
112             objectUnderTest.syncAndCreateOrUpgradeSchemaSetAndAnchor(yangModelCmHandle)
113         then: 'create schema set from module is invoked for the upgraded cm handle'
114             1 * mockCpsModuleService.createOrUpgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'upgraded-ch', [:], moduleReferences)
115         and: 'No anchor is created for the upgraded cm handle'
116             0 * mockCpsAdminService.createAnchor(*_)
117         where: 'the following parameters are used'
118             scenario      | populateCache | existingCmHandlesWithSameTag
119             'new'         | false         | []
120             'in cache'    | true          | []
121             'in database' | false         | [cmHandleWithModuleSetTag]
122     }
123
124     def 'upgrade model for a existing cm handle'() {
125         given: 'a cm handle that is ready but locked for upgrade'
126             def ncmpServiceCmHandle = new NcmpServiceCmHandle()
127             ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder()
128                 .withLockReason(MODULE_UPGRADE, 'Upgrade to ModuleSetTag: targetModuleSetTag').build())
129             ncmpServiceCmHandle.setCmHandleId('cmHandleId-1')
130             def yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle('some service name', '', '', ncmpServiceCmHandle, 'targetModuleSetTag')
131             mockCmHandleQueries.cmHandleHasState('cmHandleId-1', CmHandleState.READY) >> true
132         and: 'the module service returns some module references'
133             def moduleReferences = [new ModuleReference('module1', '1'), new ModuleReference('module2', '2')]
134             mockCpsModuleService.getYangResourcesModuleReferences(*_)>> moduleReferences
135         and: 'a cm handle with the same moduleSetTag can be found in the registry'
136             mockCmHandleQueries.queryNcmpRegistryByCpsPath("//cm-handles[@module-set-tag='targetModuleSetTag']",
137                 FetchDescendantsOption.OMIT_DESCENDANTS) >> [new DataNode(xpath: '/dmi-registry/cm-handles[@id=\'cmHandleId-1\']', leaves: ['id': 'cmHandleId-1', 'cm-handle-state': 'READY'])]
138         when: 'module upgrade is triggered'
139             objectUnderTest.syncAndCreateOrUpgradeSchemaSetAndAnchor(yangModelCmHandle)
140         then: 'the upgrade is delegated to the module service (with the correct parameters)'
141             1 * mockCpsModuleService.createOrUpgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'cmHandleId-1', Collections.emptyMap(), moduleReferences)
142     }
143
144     def 'Delete Schema Set for CmHandle'() {
145         when: 'delete schema set if exists is called'
146             objectUnderTest.deleteSchemaSetIfExists('some-cmhandle-id')
147         then: 'the module service is invoked to delete the correct schema set'
148             1 * mockCpsModuleService.deleteSchemaSet(expectedDataspaceName, 'some-cmhandle-id', CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED)
149     }
150
151     def 'Delete a non-existing Schema Set for CmHandle' () {
152         given: 'the DB throws an exception because its Schema Set does not exist'
153            mockCpsModuleService.deleteSchemaSet(*_) >> { throw new SchemaSetNotFoundException('some-dataspace-name', 'some-cmhandle-id') }
154         when: 'delete schema set if exists is called'
155             objectUnderTest.deleteSchemaSetIfExists('some-cmhandle-id')
156         then: 'the exception from the DB is ignored; there are no exceptions'
157             noExceptionThrown()
158     }
159
160     def 'Delete Schema Set for CmHandle with other exception' () {
161         given: 'an exception other than SchemaSetNotFoundException is thrown'
162             UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException();
163             1 * mockCpsModuleService.deleteSchemaSet(*_) >> { throw unsupportedOperationException }
164         when: 'delete schema set if exists is called'
165             objectUnderTest.deleteSchemaSetIfExists('some-cmhandle-id')
166         then: 'an exception is thrown'
167             def result = thrown(UnsupportedOperationException)
168             result == unsupportedOperationException
169     }
170
171     def toModuleReferences(moduleReferenceAsMap) {
172         def moduleReferences = [].withDefault { [:] }
173         moduleReferenceAsMap.forEach(property ->
174             property.forEach((moduleName, revision) -> {
175                 moduleReferences.add(new ModuleReference('moduleName' : moduleName, 'revision' : revision))
176             }))
177         return moduleReferences
178     }
179
180 }