953e1c7d0e12768926855603831b1412d3fcc19e
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2025 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.impl.inventory
23
24 import com.hazelcast.map.IMap
25 import org.onap.cps.api.CpsDataService
26 import org.onap.cps.api.exceptions.AlreadyDefinedException
27 import org.onap.cps.api.exceptions.CpsException
28 import org.onap.cps.api.exceptions.DataNodeNotFoundException
29 import org.onap.cps.api.exceptions.DataValidationException
30 import org.onap.cps.ncmp.api.exceptions.DmiRequestException
31 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState
32 import org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse
33 import org.onap.cps.ncmp.api.inventory.models.CompositeState
34 import org.onap.cps.ncmp.api.inventory.models.DmiPluginRegistration
35 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle
36 import org.onap.cps.ncmp.api.inventory.models.TrustLevel
37 import org.onap.cps.ncmp.api.inventory.models.UpgradedCmHandles
38 import org.onap.cps.ncmp.api.inventory.models.CmHandleState
39 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
40 import org.onap.cps.ncmp.impl.inventory.sync.lcm.LcmEventsCmHandleStateHandler
41 import org.onap.cps.ncmp.impl.inventory.trustlevel.TrustLevelManager
42 import spock.lang.Specification
43
44 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
45 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST
46 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
47 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
48 import static org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse.Status
49 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME
50
51 class CmHandleRegistrationServiceSpec extends Specification {
52
53     def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
54     def mockNetworkCmProxyDataServicePropertyHandler = Mock(CmHandleRegistrationServicePropertyHandler)
55     def mockInventoryPersistence = Mock(InventoryPersistence)
56     def mockCmHandleQueries = Mock(CmHandleQueryService)
57     def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
58     def mockCpsDataService = Mock(CpsDataService)
59     def mockModuleSyncStartedOnCmHandles = Mock(IMap<String, Object>)
60     def mockTrustLevelManager = Mock(TrustLevelManager)
61     def mockAlternateIdChecker = Mock(AlternateIdChecker)
62
63     def objectUnderTest = Spy(new CmHandleRegistrationService(
64         mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCpsDataService, mockLcmEventsCmHandleStateHandler,
65         mockModuleSyncStartedOnCmHandles as IMap<String, Object>, mockTrustLevelManager, mockAlternateIdChecker))
66
67     def setup() {
68         // always accept all cm handles
69         mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
70
71         // always can find all cm handles in DB
72         mockInventoryPersistence.getYangModelCmHandles(_) >> { args -> args[0].collect { new YangModelCmHandle(id:it) } }
73     }
74
75     def 'DMI Registration: Create, Update, Delete & Upgrade operations are processed in the right order'() {
76         given: 'a registration with operations of all types'
77             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
78             dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
79             dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
80             dmiRegistration.setRemovedCmHandles(['cmhandle-3'])
81             dmiRegistration.setUpgradedCmHandles(new UpgradedCmHandles(cmHandles: ['cmhandle-4', 'cmhandle-5'], moduleSetTag: moduleSetTagForUpgrade))
82         and: 'cm handles 2,3 and 4 already exist in the inventory'
83             mockInventoryPersistence.getYangModelCmHandles(['cmhandle-2']) >> [new YangModelCmHandle()]
84             mockInventoryPersistence.getYangModelCmHandles(['cmhandle-3']) >> [new YangModelCmHandle()]
85             mockInventoryPersistence.getYangModelCmHandle('cmhandle-4') >> new YangModelCmHandle(id: 'cmhandle-4', moduleSetTag: '', compositeState: new CompositeState(cmHandleState: CmHandleState.READY))
86         and: 'cm handle 5 also exist but already has the new module set tag (upgrade to)'
87             mockInventoryPersistence.getYangModelCmHandle('cmhandle-5') >> new YangModelCmHandle(id: 'cmhandle-5', moduleSetTag: moduleSetTagForUpgrade , compositeState: new CompositeState(cmHandleState: CmHandleState.READY))
88         and: 'all cm handles are in READY state'
89             mockCmHandleQueries.cmHandleHasState(_, CmHandleState.READY) >> true
90         and: 'cm handle to be removed is in progress map'
91             mockModuleSyncStartedOnCmHandles.containsKey('cmhandle-3') >> true
92         when: 'registration is processed'
93             def result = objectUnderTest.updateDmiRegistration(dmiRegistration)
94         then: 'cm-handles are removed first'
95             1 * objectUnderTest.processRemovedCmHandles(*_)
96         and: 'de-registered cm handle entry is removed from in progress map'
97             1 * mockModuleSyncStartedOnCmHandles.removeAsync('cmhandle-3')
98         then: 'updated cm handles are processed by the property handler service'
99             1 * objectUnderTest.processUpdatedCmHandles(*_)
100             1 * mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_) >> [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-2')]
101         then: 'cm-handles are upgraded'
102             1 * objectUnderTest.processUpgradedCmHandles(*_)
103         and: 'result contains the correct cm handles for each operation'
104             assert result.createdCmHandles.cmHandle == ['cmhandle-1']
105             assert result.updatedCmHandles.cmHandle == ['cmhandle-2']
106             assert result.removedCmHandles.cmHandle == ['cmhandle-3']
107             assert result.upgradedCmHandles.cmHandle as Set == ['cmhandle-4', 'cmhandle-5'] as Set
108         where: 'upgrade with and without module set tag'
109             moduleSetTagForUpgrade << ['some tag', '']
110     }
111
112     def 'DMI Registration upgrade operation with upgrade node state #scenario'() {
113         given: 'a registration with upgrade operation'
114             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
115             dmiRegistration.setUpgradedCmHandles(new UpgradedCmHandles(cmHandles: ['cmhandle-3'], moduleSetTag: 'some-module-set-tag'))
116         and: 'cm handle has the state #cmHandleState'
117             mockInventoryPersistence.getYangModelCmHandle('cmhandle-3') >> new YangModelCmHandle(id: 'cmhandle-3', moduleSetTag: '', compositeState: new CompositeState(cmHandleState: cmHandleState))
118         when: 'registration is processed'
119             def result = objectUnderTest.updateDmiRegistration(dmiRegistration)
120         then: 'upgrade operation contains expected error code'
121             assert result.upgradedCmHandles[0].status == expectedResponseStatus
122         where: 'the following parameters are used'
123             scenario    | cmHandleState        || expectedResponseStatus
124             'READY'     | CmHandleState.READY  || Status.SUCCESS
125             'Not READY' | CmHandleState.LOCKED || Status.FAILURE
126     }
127
128     def 'DMI Registration upgrade with exception #scenario'() {
129         given: 'a registration with upgrade operation'
130             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
131             dmiRegistration.setUpgradedCmHandles(new UpgradedCmHandles(cmHandles: ['cmhandle-3'], moduleSetTag: 'some-module-set-tag'))
132         and: 'exception while checking cm handle state'
133             mockInventoryPersistence.getYangModelCmHandle('cmhandle-3') >> { throw exception }
134         when: 'registration is processed'
135             def result = objectUnderTest.updateDmiRegistration(dmiRegistration)
136         then: 'upgrade operation contains expected error code'
137             assert result.upgradedCmHandles.ncmpResponseStatus.code[0] == expectedErrorCode
138         where: 'the following parameters are used'
139             scenario               | exception                                                                || expectedErrorCode
140             'data node not found'  | new DataNodeNotFoundException('some-dataspace-name', 'some-anchor-name') || '100'
141             'cm handle is invalid' | new DataValidationException('some error message', 'some error details')  || '110'
142     }
143
144     def 'DMI Registration upgrade with exception while updating CM-handle state'() {
145         given: 'a registration with upgrade operation'
146             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
147             dmiRegistration.setUpgradedCmHandles(new UpgradedCmHandles(cmHandles: ['cmhandle-3'], moduleSetTag: 'some-module-set-tag'))
148         and: 'cm handle has the state READY'
149             mockInventoryPersistence.getYangModelCmHandle('cmhandle-3') >> new YangModelCmHandle(id: 'cmhandle-3', moduleSetTag: '', compositeState: new CompositeState(cmHandleState: CmHandleState.READY))
150         and: 'exception will occur while updating cm handle state to LOCKED for upgrade'
151             mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { throw new RuntimeException() }
152         when: 'registration is processed'
153             def result = objectUnderTest.updateDmiRegistration(dmiRegistration)
154         then: 'upgrade operation contains expected error code'
155             assert result.upgradedCmHandles[0].status == Status.FAILURE
156             assert result.upgradedCmHandles[0].ncmpResponseStatus == UNKNOWN_ERROR
157     }
158
159     def 'Create CM-handle Validation: Registration with valid Service names: #scenario'() {
160         given: 'a registration '
161             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
162                 dmiDataPlugin: dmiDataPlugin)
163             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
164         when: 'update registration and sync module is called with correct DMI plugin information'
165             objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
166         then: 'create cm handles registration and sync modules is called with the correct plugin information'
167             1 * objectUnderTest.processCreatedCmHandles(dmiPluginRegistration, _)
168         where:
169             scenario                          | dmiPlugin  | dmiModelPlugin | dmiDataPlugin || expectedDmiPluginRegisteredName
170             'combined DMI plugin'             | 'service1' | ''             | ''            || 'service1'
171             'data & model DMI plugins'        | ''         | 'service1'     | 'service2'    || 'service2'
172             'data & model using same service' | ''         | 'service1'     | 'service1'    || 'service1'
173     }
174
175     def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
176         given: 'a registration '
177             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
178                 dmiDataPlugin: dmiDataPlugin)
179             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
180         when: 'registration is called with incorrect DMI plugin information'
181             objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
182         then: 'a DMI Request Exception is thrown with correct message details'
183             def exceptionThrown = thrown(DmiRequestException.class)
184             assert exceptionThrown.getMessage().contains(expectedMessageDetails)
185         and: 'registration is not called'
186             0 * objectUnderTest.processCreatedCmHandles(*_)
187         where:
188             scenario                         | dmiPlugin  | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
189             'empty DMI plugins'              | ''         | ''             | ''            || 'No DMI plugin service names'
190             'blank DMI plugins'              | ' '        | ' '            | ' '           || 'No DMI plugin service names'
191             'null DMI plugins'               | null       | null           | null          || 'No DMI plugin service names'
192             'all DMI plugins'                | 'service1' | 'service2'     | 'service3'    || 'Cannot register combined plugin service name and other service names'
193             '(combined)DMI and Data Plugin'  | 'service1' | ''             | 'service2'    || 'Cannot register combined plugin service name and other service names'
194             '(combined)DMI and model Plugin' | 'service1' | 'service2'     | ''            || 'Cannot register combined plugin service name and other service names'
195             'only model DMI plugin'          | ''         | 'service1'     | ''            || 'Cannot register just a Data or Model plugin service name'
196             'only data DMI plugin'           | ''         | ''             | 'service1'    || 'Cannot register just a Data or Model plugin service name'
197     }
198
199     def 'Create CM-Handle Successfully: #scenario.'() {
200         given: 'a registration without cm-handle properties'
201             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
202             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
203         when: 'registration is updated'
204             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
205         then: 'a successful response is received'
206             response.createdCmHandles.size() == 1
207             with(response.createdCmHandles[0]) {
208                 assert it.status == Status.SUCCESS
209                 assert it.cmHandle == 'cmhandle'
210             }
211         and: 'state handler is invoked with the expected parameters'
212             1 * mockLcmEventsCmHandleStateHandler.initiateStateAdvised(_) >> {
213                 args ->  {
214                         def yangModelCmHandles = args[0]
215                         assert yangModelCmHandles.id == ['cmhandle']
216                         assert yangModelCmHandles.dmiServiceName == ['my-server']
217                     }
218             }
219         where:
220             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
221             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
222             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || [:]                                        | '[{"name":"public-key","value":"public-value"}]'
223             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | [:]
224             'without dmi & public properties' | [:]                      | [:]                            || [:]                                        | [:]
225     }
226
227     def 'Add CM-Handle #scenario.'() {
228         given: ' registration details for one cm handles'
229             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
230                 createdCmHandles:[new NcmpServiceCmHandle(cmHandleId: 'ch-1', registrationTrustLevel: registrationTrustLevel)])
231         when: 'registration is updated'
232             objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
233         then: 'trustLevel is set for the created cm-handle'
234             1 * mockTrustLevelManager.registerCmHandles(expectedMapping)
235         where:
236             scenario                 | registrationTrustLevel || expectedMapping
237             'with trusted cm handle' | TrustLevel.COMPLETE    || [ 'ch-1' : TrustLevel.COMPLETE ]
238             'without trust level'    | null                   || [ 'ch-1' : null ]
239     }
240
241     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
242         given: 'a registration with three cm-handles to be created'
243             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
244                     createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
245                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
246                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
247         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
248             def xpath = "somePathWithId[@id='cmhandle2']"
249             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw AlreadyDefinedException.forDataNodes([xpath], 'some-context') }
250         when: 'registration is updated to create cm-handles'
251             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
252         then: 'a response is received for all cm-handles'
253             response.createdCmHandles.size() == 1
254         and: 'all cm-handles creation fails'
255             response.createdCmHandles.each {
256                 assert it.cmHandle == 'cmhandle2'
257                 assert it.status == Status.FAILURE
258                 assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
259                 assert it.errorText == 'cm-handle already exists'
260             }
261     }
262
263     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
264         given: 'a registration without cm-handle properties'
265             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
266             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
267         and: 'cm-handler registration fails: #scenario'
268             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw exception }
269         when: 'registration is updated'
270             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
271         then: 'a failure response is received'
272             response.createdCmHandles.size() == 1
273             with(response.createdCmHandles[0]) {
274                 assert it.status == Status.FAILURE
275                 assert it.cmHandle ==  'cmhandle'
276                 assert it.ncmpResponseStatus == expectedError
277                 assert it.errorText == expectedErrorText
278             }
279         where:
280             scenario                                        | exception                                                                      || expectedError           | expectedErrorText
281             'cm-handle already exist'                       | AlreadyDefinedException.forDataNodes(["path[@id='cmhandle']"], 'some-context') || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
282             'unknown exception while registering cm-handle' | new RuntimeException('Failed')                                                 || UNKNOWN_ERROR           | 'Failed'
283     }
284
285     def 'Update CM-Handle: Update Operation Response is added to the response'() {
286         given: 'a registration to update CmHandles'
287             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', updatedCmHandles: [{}])
288         and: 'cm-handle updates can be processed successfully'
289             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
290                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
291                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLES_NOT_FOUND),
292                                            CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
293             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
294         when: 'registration is updated'
295             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
296         then: 'the response contains updateOperationResponse'
297             assert response.updatedCmHandles.size() == 4
298             assert response.updatedCmHandles.containsAll(updateOperationResponse)
299     }
300
301     def 'Remove CmHandle Successfully'() {
302         given: 'a registration update to delete a cm handle'
303             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', removedCmHandles: ['cmhandle'])
304         when: 'the registration is updated'
305             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
306         then: 'the cmHandle state is set to "DELETING"'
307             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> { args -> args[0].values()[0] == CmHandleState.DELETING }
308         then: 'method to delete anchors is called once'
309             1 * mockInventoryPersistence.deleteAnchors(_)
310         and: 'method to delete relevant list/list element is called once'
311             1 * mockInventoryPersistence.deleteDataNodes(_)
312         and: 'successful response is received'
313             assert response.removedCmHandles.size() == 1
314             with(response.removedCmHandles[0]) {
315                 assert it.status == Status.SUCCESS
316                 assert it.cmHandle == 'cmhandle'
317             }
318         and: 'the cmHandle state is updated to "DELETED"'
319             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >>  { args -> args[0].values()[0] == CmHandleState.DELETED }
320     }
321
322     def 'Remove CmHandle: Partial Success'() {
323         given: 'a registration with three cm-handles to be deleted'
324             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
325                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
326         and: 'cm handles to be deleted in the progress map'
327             mockModuleSyncStartedOnCmHandles.containsKey("cmhandle1") >> true
328             mockModuleSyncStartedOnCmHandles.containsKey("cmhandle3") >> true
329         and: 'delete fails for batch. Retry only fails for and cm handle 2'
330             mockInventoryPersistence.deleteDataNodes(_) >> { throw new RuntimeException("Batch Failed") }
331                                                         >> { /* cm handle 1 is OK */ }
332                                                         >> { throw new RuntimeException("Cm handle 2 Failed")}
333                                                         >> { /* cm handle 3 is OK */ }
334         when: 'registration is updated to delete cmhandles'
335             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
336         then: 'the cmHandle states are all updated to "DELETING"'
337             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({ assert it.every { entry -> entry.value == CmHandleState.DELETING } })
338         and: 'a response is received for all cm-handles'
339             response.removedCmHandles.size() == 3
340         and: 'successfully de-registered cm handle 1 is removed from in progress map'
341             1 * mockModuleSyncStartedOnCmHandles.removeAsync('cmhandle1')
342         and: 'successfully de-registered cm handle 3 is removed from in progress map even though it was already being removed'
343             1 * mockModuleSyncStartedOnCmHandles.removeAsync('cmhandle3')
344         and: 'failed de-registered cm handle entries should NOT be removed from in progress map'
345             0 * mockModuleSyncStartedOnCmHandles.removeAsync('cmhandle2')
346         and: '1st and 3rd cm-handle deletes successfully'
347             with(response.removedCmHandles[0]) {
348                 assert it.status == Status.SUCCESS
349                 assert it.cmHandle == 'cmhandle1'
350             }
351             with(response.removedCmHandles[2]) {
352                 assert it.status == Status.SUCCESS
353                 assert it.cmHandle == 'cmhandle3'
354             }
355         and: '2nd cm-handle deletion fails'
356             with(response.removedCmHandles[1]) {
357                 assert it.status == Status.FAILURE
358                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
359                 assert it.errorText == 'Cm handle 2 Failed'
360                 assert it.cmHandle == 'cmhandle2'
361             }
362         and: 'the cmHandle state is updated to DELETED for 1st and 3rd'
363             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({
364                 assert it.size() == 2
365                 assert it.every { entry -> entry.value == CmHandleState.DELETED }
366             })
367     }
368
369     def 'Remove CmHandle Error Handling: #scenario'() {
370         given: 'a registration'
371             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', removedCmHandles: ['cmhandle'])
372         and: 'cm-handle deletion fails on batch'
373             mockInventoryPersistence.deleteDataNodes(_) >> { throw deleteListElementException }
374         and: 'cm-handle deletion fails on individual delete'
375             mockInventoryPersistence.deleteDataNode(_) >> { throw deleteListElementException }
376         when: 'registration is updated to delete cmhandle'
377             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
378         then: 'a failure response is received'
379             assert response.removedCmHandles.size() == 1
380             with(response.removedCmHandles[0]) {
381                 assert it.status == Status.FAILURE
382                 assert it.cmHandle == 'cmhandle'
383                 assert it.ncmpResponseStatus == expectedError
384                 assert it.errorText == expectedErrorText
385             }
386         and: 'the cm handle state is not updated to "DELETED"'
387             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_, CmHandleState.DELETED)
388         where:
389         scenario                     | deleteListElementException                || expectedError        | expectedErrorText
390         'cm-handle does not exist'   | new DataNodeNotFoundException('', '', '') || CM_HANDLES_NOT_FOUND | 'cm handle reference(s) not found'
391         'cm-handle has invalid name' | new DataValidationException('', '')       || CM_HANDLE_INVALID_ID | 'cm handle reference has an invalid character(s) in id'
392         'an unexpected exception'    | new RuntimeException('Failed')            || UNKNOWN_ERROR        | 'Failed'
393     }
394
395     def 'Set Cm Handle Data Sync Enabled Flag where data sync flag is #scenario'() {
396         given: 'an existing cm handle composite state'
397             def compositeState = new CompositeState(cmHandleState: CmHandleState.READY, dataSyncEnabled: initialDataSyncEnabledFlag,
398                 dataStores: CompositeState.DataStores.builder()
399                     .operationalDataStore(CompositeState.Operational.builder()
400                         .dataStoreSyncState(initialDataSyncState)
401                         .build()).build())
402         and: 'get cm handle state returns the composite state for the given cm handle id'
403             mockInventoryPersistence.getCmHandleState('some-cm-handle-id') >> compositeState
404         when: 'set data sync enabled is called with the data sync enabled flag set to #dataSyncEnabledFlag'
405             objectUnderTest.setDataSyncEnabled('some-cm-handle-id', dataSyncEnabledFlag)
406         then: 'the data sync enabled flag is set to #dataSyncEnabled'
407             compositeState.dataSyncEnabled == dataSyncEnabledFlag
408         and: 'the data store sync state is set to #expectedDataStoreSyncState'
409             compositeState.dataStores.operationalDataStore.dataStoreSyncState == expectedDataStoreSyncState
410         and: 'the cps data service to delete data nodes is invoked the expected number of times'
411             deleteDataNodeExpectedNumberOfInvocation * mockCpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'some-cm-handle-id', '/netconf-state', _)
412         and: 'the inventory persistence service to update node leaves is called with the correct values'
413             saveCmHandleStateExpectedNumberOfInvocations * mockInventoryPersistence.saveCmHandleState('some-cm-handle-id', compositeState)
414         where: 'the following data sync enabled flag is used'
415             scenario                                              | dataSyncEnabledFlag | initialDataSyncEnabledFlag | initialDataSyncState               || expectedDataStoreSyncState         | deleteDataNodeExpectedNumberOfInvocation | saveCmHandleStateExpectedNumberOfInvocations
416             'enabled'                                             | true                | false                      | DataStoreSyncState.NONE_REQUESTED  || DataStoreSyncState.UNSYNCHRONIZED  | 0                                        | 1
417             'disabled'                                            | false               | true                       | DataStoreSyncState.UNSYNCHRONIZED  || DataStoreSyncState.NONE_REQUESTED  | 0                                        | 1
418             'disabled where sync-state is currently SYNCHRONIZED' | false               | true                       | DataStoreSyncState.SYNCHRONIZED    || DataStoreSyncState.NONE_REQUESTED  | 1                                        | 1
419             'is set to existing flag state'                       | true                | true                       | DataStoreSyncState.UNSYNCHRONIZED  || DataStoreSyncState.UNSYNCHRONIZED  | 0                                        | 0
420     }
421
422     def 'Set cm Handle Data Sync Enabled flag with following cm handle not in ready state exception' () {
423         given: 'a cm handle composite state'
424             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED, dataSyncEnabled: false)
425         and: 'get cm handle state returns the composite state for the given cm handle id'
426             mockInventoryPersistence.getCmHandleState('some-cm-handle-id') >> compositeState
427         when: 'set data sync enabled is called with the data sync enabled flag set to true'
428             objectUnderTest.setDataSyncEnabled('some-cm-handle-id', true)
429         then: 'the expected exception is thrown'
430             thrown(CpsException)
431         and: 'the inventory persistence service to update node leaves is not invoked'
432             0 * mockInventoryPersistence.saveCmHandleState(_, _)
433     }
434
435 }