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