Merge "Add withTrustLevel condition to CmHandle Query API"
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / inventory / sync / ModuleSyncTasksSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 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.inventory.sync
23
24 import com.hazelcast.config.Config
25 import com.hazelcast.instance.impl.HazelcastInstanceFactory
26 import com.hazelcast.map.IMap
27 import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler
28 import org.onap.cps.ncmp.api.impl.inventory.sync.ModuleSyncService
29 import org.onap.cps.ncmp.api.impl.inventory.sync.ModuleSyncTasks
30 import org.onap.cps.ncmp.api.impl.inventory.sync.SyncUtils
31 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
32 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState
33 import org.onap.cps.ncmp.api.impl.inventory.CompositeState
34 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder
35 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence
36 import org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory
37 import org.onap.cps.spi.model.DataNode
38 import spock.lang.Specification
39 import java.util.concurrent.atomic.AtomicInteger
40
41 class ModuleSyncTasksSpec extends Specification {
42
43     def mockInventoryPersistence = Mock(InventoryPersistence)
44
45     def mockSyncUtils = Mock(SyncUtils)
46
47     def mockModuleSyncService = Mock(ModuleSyncService)
48
49     def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
50
51     IMap<String, Object> moduleSyncStartedOnCmHandles = HazelcastInstanceFactory
52             .getOrCreateHazelcastInstance(new Config('hazelcastInstanceName'))
53             .getMap('mapInstanceName')
54
55     def batchCount = new AtomicInteger(5)
56
57     def objectUnderTest = new ModuleSyncTasks(mockInventoryPersistence, mockSyncUtils, mockModuleSyncService,
58             mockLcmEventsCmHandleStateHandler, moduleSyncStartedOnCmHandles)
59
60     def 'Module Sync ADVISED cm handles.'() {
61         given: 'cm handles in an ADVISED state'
62             def cmHandle1 = advisedCmHandleAsDataNode('cm-handle-1')
63             def cmHandle2 = advisedCmHandleAsDataNode('cm-handle-2')
64         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
65             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
66         when: 'module sync poll is executed'
67             objectUnderTest.performModuleSync([cmHandle1, cmHandle2], batchCount)
68         then: 'module sync service deletes schemas set of each cm handle if it already exists'
69             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-1')
70             1 * mockModuleSyncService.deleteSchemaSetIfExists('cm-handle-2')
71         and: 'module sync service is invoked for each cm handle'
72             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
73             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-2') }
74         and: 'the state handler is called for the both cm handles'
75             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
76                 assertBatch(args, ['cm-handle-1', 'cm-handle-2'], CmHandleState.READY)
77             }
78         and: 'batch count is decremented by one'
79             assert batchCount.get() == 4
80     }
81
82     def 'Module Sync ADVISED cm handle with failure during sync.'() {
83         given: 'a cm handle in an ADVISED state'
84             def cmHandle = advisedCmHandleAsDataNode('cm-handle')
85         and: 'the inventory persistence cm handle returns a ADVISED state for the cm handle'
86             def cmHandleState = new CompositeState(cmHandleState: CmHandleState.ADVISED)
87             1 * mockInventoryPersistence.getCmHandleState('cm-handle') >> cmHandleState
88         and: 'module sync service attempts to sync the cm handle and throws an exception'
89             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(*_) >> { throw new Exception('some exception') }
90         when: 'module sync is executed'
91             objectUnderTest.performModuleSync([cmHandle], batchCount)
92         then: 'update lock reason, details and attempts is invoked'
93             1 * mockSyncUtils.updateLockReasonDetailsAndAttempts(cmHandleState, LockReasonCategory.MODULE_SYNC_FAILED, 'some exception')
94         and: 'the state handler is called to update the state to LOCKED'
95             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args ->
96                 assertBatch(args, ['cm-handle'], CmHandleState.LOCKED)
97             }
98         and: 'batch count is decremented by one'
99             assert batchCount.get() == 4
100     }
101
102     def 'Reset failed CM Handles #scenario.'() {
103         given: 'cm handles in an locked state'
104             def lockedState = new CompositeStateBuilder().withCmHandleState(CmHandleState.LOCKED)
105                     .withLockReason(LockReasonCategory.MODULE_SYNC_FAILED, '').withLastUpdatedTimeNow().build()
106             def yangModelCmHandle1 = new YangModelCmHandle(id: 'cm-handle-1', compositeState: lockedState)
107             def yangModelCmHandle2 = new YangModelCmHandle(id: 'cm-handle-2', compositeState: lockedState)
108             def expectedCmHandleStatePerCmHandle = [(yangModelCmHandle1): CmHandleState.ADVISED]
109         and: 'clear in progress map'
110             resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles)
111         and: 'add cm handle entry into progress map'
112             moduleSyncStartedOnCmHandles.put('cm-handle-1', 'started')
113             moduleSyncStartedOnCmHandles.put('cm-handle-2', 'started')
114         and: 'sync utils retry locked cm handle returns #isReadyForRetry'
115             mockSyncUtils.needsModuleSyncRetryOrUpgrade(lockedState) >>> isReadyForRetry
116         when: 'resetting failed cm handles'
117             objectUnderTest.resetFailedCmHandles([yangModelCmHandle1, yangModelCmHandle2])
118         then: 'updated to state "ADVISED" from "READY" is called as often as there are cm handles ready for retry'
119             expectedNumberOfInvocationsToUpdateCmHandleState * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(expectedCmHandleStatePerCmHandle)
120         and: 'after reset performed size of in progress map'
121             assert moduleSyncStartedOnCmHandles.size() == inProgressMapSize
122         where:
123             scenario                        | isReadyForRetry | inProgressMapSize || expectedNumberOfInvocationsToUpdateCmHandleState
124             'retry locked cm handle'        | [true, false]   | 1                 || 1
125             'do not retry locked cm handle' | [false, false]  | 2                 || 0
126     }
127
128     def 'Module Sync ADVISED cm handle without entry in progress map.'() {
129         given: 'cm handles in an ADVISED state'
130             def cmHandle1 = advisedCmHandleAsDataNode('cm-handle-1')
131         and: 'the inventory persistence cm handle returns a ADVISED state for the any handle'
132             mockInventoryPersistence.getCmHandleState(_) >> new CompositeState(cmHandleState: CmHandleState.ADVISED)
133         and: 'entry in progress map for other cm handle'
134             moduleSyncStartedOnCmHandles.put('other-cm-handle', 'started')
135         when: 'module sync poll is executed'
136             objectUnderTest.performModuleSync([cmHandle1], batchCount)
137         then: 'module sync service is invoked for cm handle'
138             1 * mockModuleSyncService.syncAndCreateOrUpgradeSchemaSetAndAnchor(_) >> { args -> assertYamgModelCmHandleArgument(args, 'cm-handle-1') }
139         and: 'the entry for other cm handle is still in the progress map'
140             assert moduleSyncStartedOnCmHandles.get('other-cm-handle') != null
141     }
142
143     def advisedCmHandleAsDataNode(cmHandleId) {
144         return new DataNode(anchorName: cmHandleId, leaves: ['id': cmHandleId, 'cm-handle-state': 'ADVISED'])
145     }
146
147     def assertYamgModelCmHandleArgument(args, expectedCmHandleId) {
148         {
149             def yangModelCmHandle = args[0]
150             assert yangModelCmHandle.id == expectedCmHandleId
151         }
152         return true
153     }
154
155     def assertBatch(args, expectedCmHandleStatePerCmHandleIds, expectedCmHandleState) {
156         {
157             Map<YangModelCmHandle, CmHandleState> actualCmHandleStatePerCmHandle = args[0]
158             assert actualCmHandleStatePerCmHandle.size() == expectedCmHandleStatePerCmHandleIds.size()
159             actualCmHandleStatePerCmHandle.each {
160                 assert expectedCmHandleStatePerCmHandleIds.contains(it.key.id)
161                 assert it.value == expectedCmHandleState
162             }
163         }
164         return true
165     }
166
167     def resetModuleSyncStartedOnCmHandles(moduleSyncStartedOnCmHandles) {
168         moduleSyncStartedOnCmHandles.clear();
169     }
170 }