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