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