Correct use of Spock setup and cleanup methods (no need for @Before @After)
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / inventory / sync / ModuleSyncTasksSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 Nordix Foundation
4  *  Modifications Copyright (C) 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
22 package org.onap.cps.ncmp.api.impl.inventory.sync
23
24 import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_SYNC_FAILED
25 import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_UPGRADE_FAILED
26
27 import ch.qos.logback.classic.Level
28 import ch.qos.logback.classic.Logger
29 import ch.qos.logback.classic.spi.ILoggingEvent
30 import ch.qos.logback.core.read.ListAppender
31 import com.hazelcast.config.Config
32 import com.hazelcast.instance.impl.HazelcastInstanceFactory
33 import com.hazelcast.map.IMap
34 import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler
35 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
36 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState
37 import org.onap.cps.ncmp.api.impl.inventory.CompositeState
38 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder
39 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence
40 import org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory
41 import org.onap.cps.spi.model.DataNode
42 import org.slf4j.LoggerFactory
43 import spock.lang.Specification
44 import java.util.concurrent.atomic.AtomicInteger
45
46 class ModuleSyncTasksSpec extends Specification {
47
48     def logger = Spy(ListAppender<ILoggingEvent>)
49
50     void setup() {
51         ((Logger) LoggerFactory.getLogger(ModuleSyncTasks.class)).addAppender(logger)
52         logger.start()
53     }
54
55     void cleanup() {
56         ((Logger) LoggerFactory.getLogger(ModuleSyncTasks.class)).detachAndStopAllAppenders()
57     }
58
59     def mockInventoryPersistence = Mock(InventoryPersistence)
60
61     def mockSyncUtils = Mock(ModuleOperationsUtils)
62
63     def mockModuleSyncService = Mock(ModuleSyncService)
64
65     def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
66
67     IMap<String, Object> moduleSyncStartedOnCmHandles = HazelcastInstanceFactory
68             .getOrCreateHazelcastInstance(new Config('hazelcastInstanceName'))
69             .getMap('mapInstanceName')
70
71     def batchCount = new AtomicInteger(5)
72
73     def objectUnderTest = new ModuleSyncTasks(mockInventoryPersistence, mockSyncUtils, mockModuleSyncService,
74             mockLcmEventsCmHandleStateHandler, moduleSyncStartedOnCmHandles)
75
76     def 'Module Sync ADVISED cm handles.'() {
77         given: 'cm handles in an ADVISED state'
78             def cmHandle1 = cmHandleAsDataNodeByIdAndState('cm-handle-1', CmHandleState.ADVISED)
79             def cmHandle2 = cmHandleAsDataNodeByIdAndState('cm-handle-2', CmHandleState.ADVISED)
80         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
81             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
82         when: 'module sync poll is executed'
83             objectUnderTest.performModuleSync([cmHandle1, cmHandle2], batchCount)
84         then: 'module sync service deletes schemas set of each cm handle if it already exists'
85             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-1')
86             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-2')
87         and: 'module sync service is invoked for each cm handle'
88             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
89             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-2') }
90         and: 'the state handler is called for the both cm handles'
91             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
92                 assertBatch(args, ['cm-handle-1', 'cm-handle-2'], CmHandleState.READY)
93             }
94         and: 'batch count is decremented by one'
95             assert batchCount.get() == 4
96     }
97
98     def 'Module Sync ADVISED cm handle with failure during sync.'() {
99         given: 'a cm handle in an ADVISED state'
100             def cmHandle = cmHandleAsDataNodeByIdAndState('cm-handle', CmHandleState.ADVISED)
101         and: 'the inventory persistence cm handle returns a ADVISED state for the cm handle'
102             def cmHandleState = new CompositeState(cmHandleState: CmHandleState.ADVISED)
103             1 * mockInventoryPersistence.getCmHandleState('cm-handle') >> cmHandleState
104         and: 'module sync service attempts to sync the cm handle and throws an exception'
105             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(*_) >> { throw new Exception('some exception') }
106         when: 'module sync is executed'
107             objectUnderTest.performModuleSync([cmHandle], batchCount)
108         then: 'update lock reason, details and attempts is invoked'
109             1 * mockSyncUtils.updateLockReasonDetailsAndAttempts(cmHandleState, MODULE_SYNC_FAILED, 'some exception')
110         and: 'the state handler is called to update the state to LOCKED'
111             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
112                 assertBatch(args, ['cm-handle'], CmHandleState.LOCKED)
113             }
114         and: 'batch count is decremented by one'
115             assert batchCount.get() == 4
116     }
117
118     def 'Failed cm handle during #scenario.'() {
119         given: 'a cm handle in LOCKED state'
120             def cmHandle = cmHandleAsDataNodeByIdAndState('cm-handle', CmHandleState.LOCKED)
121         and: 'the inventory persistence cm handle returns a LOCKED state with reason for the cm handle'
122             def expectedCmHandleState = new CompositeState(cmHandleState: cmHandleState, lockReason: CompositeState
123                 .LockReason.builder().lockReasonCategory(lockReasonCategory).details(lockReasonDetails).build())
124             1 * mockInventoryPersistence.getCmHandleState('cm-handle') >> expectedCmHandleState
125         and: 'module sync service attempts to sync/upgrade the cm handle and throws an exception'
126             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(*_) >> { throw new Exception('some exception') }
127         when: 'module sync is executed'
128             objectUnderTest.performModuleSync([cmHandle], batchCount)
129         then: 'update lock reason, details and attempts is invoked'
130             1 * mockSyncUtils.updateLockReasonDetailsAndAttempts(expectedCmHandleState, expectedLockReasonCategory, 'some exception')
131         where:
132             scenario         | cmHandleState        | lockReasonCategory    | lockReasonDetails                              || expectedLockReasonCategory
133             'module upgrade' | CmHandleState.LOCKED | MODULE_UPGRADE_FAILED | 'Upgrade to ModuleSetTag: some-module-set-tag' || MODULE_UPGRADE_FAILED
134             'module sync'    | CmHandleState.LOCKED | MODULE_SYNC_FAILED    | 'some lock details'                            || MODULE_SYNC_FAILED
135     }
136
137     def 'Reset failed CM Handles #scenario.'() {
138         given: 'cm handles in an locked state'
139             def lockedState = new CompositeStateBuilder().withCmHandleState(CmHandleState.LOCKED)
140                     .withLockReason(LockReasonCategory.MODULE_SYNC_FAILED, '').withLastUpdatedTimeNow().build()
141             def yangModelCmHandle1 = new YangModelCmHandle(id: 'cm-handle-1', compositeState: lockedState)
142             def yangModelCmHandle2 = new YangModelCmHandle(id: 'cm-handle-2', compositeState: lockedState)
143             def expectedCmHandleStatePerCmHandle = [(yangModelCmHandle1): CmHandleState.ADVISED]
144         and: 'clear in progress map'
145             resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles)
146         and: 'add cm handle entry into progress map'
147             moduleSyncStartedOnCmHandles.put('cm-handle-1', 'started')
148             moduleSyncStartedOnCmHandles.put('cm-handle-2', 'started')
149         and: 'sync utils retry locked cm handle returns #isReadyForRetry'
150             mockSyncUtils.needsModuleSyncRetryOrUpgrade(lockedState) >>> isReadyForRetry
151         when: 'resetting failed cm handles'
152             objectUnderTest.resetFailedCmHandles([yangModelCmHandle1, yangModelCmHandle2])
153         then: 'updated to state "ADVISED" from "READY" is called as often as there are cm handles ready for retry'
154             expectedNumberOfInvocationsToUpdateCmHandleState * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(expectedCmHandleStatePerCmHandle)
155         and: 'after reset performed size of in progress map'
156             assert moduleSyncStartedOnCmHandles.size() == inProgressMapSize
157         where:
158             scenario                        | isReadyForRetry | inProgressMapSize || expectedNumberOfInvocationsToUpdateCmHandleState
159             'retry locked cm handle'        | [true, false]   | 1                 || 1
160             'do not retry locked cm handle' | [false, false]  | 2                 || 0
161     }
162
163     def 'Module Sync ADVISED cm handle without entry in progress map.'() {
164         given: 'cm handles in an ADVISED state'
165             def cmHandle1 = cmHandleAsDataNodeByIdAndState('cm-handle-1', CmHandleState.ADVISED)
166         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
167             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
168         and: 'entry in progress map for other cm handle'
169             moduleSyncStartedOnCmHandles.put('other-cm-handle', 'started')
170         when: 'module sync poll is executed'
171             objectUnderTest.performModuleSync([cmHandle1], batchCount)
172         then: 'module sync service is invoked for cm handle'
173             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
174         and: 'the entry for other cm handle is still in the progress map'
175             assert moduleSyncStartedOnCmHandles.get('other-cm-handle') != null
176     }
177
178     def 'Remove already processed cm handle id from hazelcast map'() {
179         given: 'hazelcast map contains cm handle id'
180             moduleSyncStartedOnCmHandles.put('ch-1', 'started')
181         when: 'remove cm handle entry'
182             objectUnderTest.removeResetCmHandleFromModuleSyncMap('ch-1')
183         then: 'an event is logged with level INFO'
184             def loggingEvent = getLoggingEvent()
185             assert loggingEvent.level == Level.INFO
186         and: 'the log indicates the cm handle entry is removed successfully'
187             assert loggingEvent.formattedMessage == 'ch-1 removed from in progress map'
188     }
189
190     def 'Remove non-existing cm handle id from hazelcast map'() {
191         given: 'hazelcast map does not contains cm handle id'
192             def result = moduleSyncStartedOnCmHandles.get('non-existing-cm-handle')
193             assert result == null
194         when: 'remove cm handle entry from  hazelcast map'
195             objectUnderTest.removeResetCmHandleFromModuleSyncMap('non-existing-cm-handle')
196         then: 'no event is logged'
197             def loggingEvent = getLoggingEvent()
198             assert loggingEvent == null
199     }
200
201     def cmHandleAsDataNodeByIdAndState(cmHandleId, cmHandleState) {
202         return new DataNode(anchorName: cmHandleId, leaves: ['id': cmHandleId, 'cm-handle-state': cmHandleState])
203     }
204
205     def assertYamgModelCmHandleArgument(args, expectedCmHandleId) {
206         {
207             def yangModelCmHandle = args[0]
208             assert yangModelCmHandle.id == expectedCmHandleId
209         }
210         return true
211     }
212
213     def assertBatch(args, expectedCmHandleStatePerCmHandleIds, expectedCmHandleState) {
214         {
215             Map<YangModelCmHandle, CmHandleState> actualCmHandleStatePerCmHandle = args[0]
216             assert actualCmHandleStatePerCmHandle.size() == expectedCmHandleStatePerCmHandleIds.size()
217             actualCmHandleStatePerCmHandle.each {
218                 assert expectedCmHandleStatePerCmHandleIds.contains(it.key.id)
219                 assert it.value == expectedCmHandleState
220             }
221         }
222         return true
223     }
224
225     def resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles) {
226         moduleSyncStartedOnCmHandles.clear();
227     }
228
229     def getLoggingEvent() {
230         return logger.list[0]
231     }
232 }