ff190cc1caa4250684b28c1552f2d446de4a60b2
[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.DataStoreSyncState
29 import org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse
30 import org.onap.cps.ncmp.api.inventory.models.CompositeState
31 import org.onap.cps.ncmp.api.inventory.models.DmiPluginRegistration
32 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle
33 import org.onap.cps.ncmp.api.inventory.models.TrustLevel
34 import org.onap.cps.ncmp.api.inventory.models.UpgradedCmHandles
35 import org.onap.cps.ncmp.api.inventory.models.CmHandleState
36 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
37 import org.onap.cps.ncmp.impl.inventory.sync.lcm.LcmEventsCmHandleStateHandler
38 import org.onap.cps.ncmp.impl.inventory.trustlevel.TrustLevelManager
39 import org.onap.cps.api.exceptions.AlreadyDefinedException
40 import org.onap.cps.api.exceptions.CpsException
41 import org.onap.cps.api.exceptions.DataNodeNotFoundException
42 import org.onap.cps.api.exceptions.DataValidationException
43 import org.onap.cps.api.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 mockTrustLevelManager = Mock(TrustLevelManager)
64     def mockAlternateIdChecker = Mock(AlternateIdChecker)
65
66     def objectUnderTest = Spy(new CmHandleRegistrationService(
67         mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCpsDataService, mockLcmEventsCmHandleStateHandler,
68         mockModuleSyncStartedOnCmHandles as IMap<String, Object>, 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         and: 'cm handles is present in in-progress map'
91             mockModuleSyncStartedOnCmHandles.containsKey('cmhandle-2') >> true
92         when: 'registration is processed'
93             objectUnderTest.updateDmiRegistration(dmiRegistration)
94         then: 'cm-handles are removed first'
95             1 * objectUnderTest.processRemovedCmHandles(*_)
96         and: 'de-registered cm handle entry is removed from in progress map'
97             1 * mockModuleSyncStartedOnCmHandles.removeAsync('cmhandle-2')
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.updateDmiRegistration(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.updateDmiRegistration(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.updateDmiRegistration(dmiPluginRegistration)
144         then: 'create cm handles registration and sync modules is called with the correct plugin information'
145             1 * objectUnderTest.processCreatedCmHandles(dmiPluginRegistration, _)
146         where:
147             scenario                          | dmiPlugin  | dmiModelPlugin | dmiDataPlugin || expectedDmiPluginRegisteredName
148             'combined DMI plugin'             | 'service1' | ''             | ''            || 'service1'
149             'data & model DMI plugins'        | ''         | 'service1'     | 'service2'    || 'service2'
150             'data & model using same service' | ''         | 'service1'     | 'service1'    || 'service1'
151     }
152
153     def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
154         given: 'a registration '
155             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
156                 dmiDataPlugin: dmiDataPlugin)
157             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
158         when: 'registration is called with incorrect DMI plugin information'
159             objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
160         then: 'a DMI Request Exception is thrown with correct message details'
161             def exceptionThrown = thrown(DmiRequestException.class)
162             assert exceptionThrown.getMessage().contains(expectedMessageDetails)
163         and: 'registration is not called'
164             0 * objectUnderTest.processCreatedCmHandles(*_)
165         where:
166             scenario                         | dmiPlugin  | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
167             'empty DMI plugins'              | ''         | ''             | ''            || 'No DMI plugin service names'
168             'blank DMI plugins'              | ' '        | ' '            | ' '           || 'No DMI plugin service names'
169             'null DMI plugins'               | null       | null           | null          || 'No DMI plugin service names'
170             'all DMI plugins'                | 'service1' | 'service2'     | 'service3'    || 'Cannot register combined plugin service name and other service names'
171             '(combined)DMI and Data Plugin'  | 'service1' | ''             | 'service2'    || 'Cannot register combined plugin service name and other service names'
172             '(combined)DMI and model Plugin' | 'service1' | 'service2'     | ''            || 'Cannot register combined plugin service name and other service names'
173             'only model DMI plugin'          | ''         | 'service1'     | ''            || 'Cannot register just a Data or Model plugin service name'
174             'only data DMI plugin'           | ''         | ''             | 'service1'    || 'Cannot register just a Data or Model plugin service name'
175     }
176
177     def 'Create CM-Handle Successfully: #scenario.'() {
178         given: 'a registration without cm-handle properties'
179             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
180             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
181         when: 'registration is updated'
182             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
183         then: 'a successful response is received'
184             response.createdCmHandles.size() == 1
185             with(response.createdCmHandles[0]) {
186                 assert it.status == Status.SUCCESS
187                 assert it.cmHandle == 'cmhandle'
188             }
189         and: 'state handler is invoked with the expected parameters'
190             1 * mockLcmEventsCmHandleStateHandler.initiateStateAdvised(_) >> {
191                 args ->  {
192                         def yangModelCmHandles = args[0]
193                         assert yangModelCmHandles.id == ['cmhandle']
194                         assert yangModelCmHandles.dmiServiceName == ['my-server']
195                     }
196             }
197         where:
198             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
199             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
200             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || [:]                                        | '[{"name":"public-key","value":"public-value"}]'
201             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | [:]
202             'without dmi & public properties' | [:]                      | [:]                            || [:]                                        | [:]
203     }
204
205     def 'Add CM-Handle #scenario.'() {
206         given: ' registration details for one cm handles'
207             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
208                 createdCmHandles:[new NcmpServiceCmHandle(cmHandleId: 'ch-1', registrationTrustLevel: registrationTrustLevel)])
209         when: 'registration is updated'
210             objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
211         then: 'trustLevel is set for the created cm-handle'
212             1 * mockTrustLevelManager.registerCmHandles(expectedMapping)
213         where:
214             scenario                 | registrationTrustLevel || expectedMapping
215             'with trusted cm handle' | TrustLevel.COMPLETE    || [ 'ch-1' : TrustLevel.COMPLETE ]
216             'without trust level'    | null                   || [ 'ch-1' : null ]
217     }
218
219     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
220         given: 'a registration with three cm-handles to be created'
221             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
222                     createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
223                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
224                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
225         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
226             def xpath = "somePathWithId[@id='cmhandle2']"
227             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw AlreadyDefinedException.forDataNodes([xpath], 'some-context') }
228         when: 'registration is updated to create cm-handles'
229             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
230         then: 'a response is received for all cm-handles'
231             response.createdCmHandles.size() == 1
232         and: 'all cm-handles creation fails'
233             response.createdCmHandles.each {
234                 assert it.cmHandle == 'cmhandle2'
235                 assert it.status == Status.FAILURE
236                 assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
237                 assert it.errorText == 'cm-handle already exists'
238             }
239     }
240
241     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
242         given: 'a registration without cm-handle properties'
243             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
244             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
245         and: 'cm-handler registration fails: #scenario'
246             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw exception }
247         when: 'registration is updated'
248             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
249         then: 'a failure response is received'
250             response.createdCmHandles.size() == 1
251             with(response.createdCmHandles[0]) {
252                 assert it.status == Status.FAILURE
253                 assert it.cmHandle ==  'cmhandle'
254                 assert it.ncmpResponseStatus == expectedError
255                 assert it.errorText == expectedErrorText
256             }
257         where:
258             scenario                                        | exception                                                                      || expectedError           | expectedErrorText
259             'cm-handle already exist'                       | AlreadyDefinedException.forDataNodes(["path[@id='cmhandle']"], 'some-context') || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
260             'unknown exception while registering cm-handle' | new RuntimeException('Failed')                                                 || UNKNOWN_ERROR           | 'Failed'
261     }
262
263     def 'Update CM-Handle: Update Operation Response is added to the response'() {
264         given: 'a registration to update CmHandles'
265             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', updatedCmHandles: [{}])
266         and: 'cm-handle updates can be processed successfully'
267             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
268                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
269                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLES_NOT_FOUND),
270                                            CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
271             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
272         when: 'registration is updated'
273             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
274         then: 'the response contains updateOperationResponse'
275             assert response.updatedCmHandles.size() == 4
276             assert response.updatedCmHandles.containsAll(updateOperationResponse)
277     }
278
279     def 'Remove CmHandle Successfully: #scenario'() {
280         given: 'a registration'
281             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', removedCmHandles: ['cmhandle'])
282         and: '#scenario'
283             mockCpsModuleService.deleteSchemaSetsWithCascade(_, ['cmhandle']) >>  { if (!schemaSetExist) { throw new SchemaSetNotFoundException('', '') } }
284         when: 'registration is updated to delete cmhandle'
285             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
286         then: 'the cmHandle state is updated to "DELETING"'
287             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >>
288                 { args -> args[0].values()[0] == CmHandleState.DELETING }
289         then: 'method to delete relevant schema set is called once'
290             1 * mockInventoryPersistence.deleteSchemaSetsWithCascade(_)
291         and: 'method to delete relevant list/list element is called once'
292             1 * mockInventoryPersistence.deleteDataNodes(_)
293         and: 'successful response is received'
294             assert response.removedCmHandles.size() == 1
295             with(response.removedCmHandles[0]) {
296                 assert it.status == Status.SUCCESS
297                 assert it.cmHandle == 'cmhandle'
298             }
299         and: 'the cmHandle state is updated to "DELETED"'
300             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >>
301                 { args -> args[0].values()[0] == CmHandleState.DELETED }
302         and: 'No cm handles state updates for "upgraded cm handles"'
303             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch([:])
304         where:
305             scenario                                            | schemaSetExist
306             'schema-set exists and can be deleted successfully' | true
307             'schema-set does not exist'                         | false
308     }
309
310     def 'Remove CmHandle: Partial Success'() {
311         given: 'a registration with three cm-handles to be deleted'
312             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
313                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
314         and: 'cm handles to be deleted in the progress map'
315             mockModuleSyncStartedOnCmHandles.containsKey("cmhandle1") >> true
316             mockModuleSyncStartedOnCmHandles.containsKey("cmhandle3") >> true
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.updateDmiRegistration(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.removeAsync('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.removeAsync('cmhandle3')
331         and: 'failed de-registered cm handle entries should NOT be removed from in progress map'
332             0 * mockModuleSyncStartedOnCmHandles.removeAsync('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     def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
359         given: 'a registration'
360             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
361                 removedCmHandles: ['cmhandle'])
362         and: 'schema set batch deletion failed with unknown error'
363             mockInventoryPersistence.deleteSchemaSetsWithCascade(_) >> { throw new RuntimeException('Failed') }
364         and: 'schema set single deletion failed with unknown error'
365             mockInventoryPersistence.deleteSchemaSetWithCascade(_) >> { throw new RuntimeException('Failed') }
366         when: 'registration is updated to delete cmhandle'
367             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
368         then: 'no exception is thrown'
369             noExceptionThrown()
370         and: 'cm-handle is not deleted'
371             0 * mockInventoryPersistence.deleteDataNodes(_)
372         and: 'the cmHandle state is not updated to "DELETED"'
373             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch([yangModelCmHandle: CmHandleState.DELETED])
374         and: 'a failure response is received'
375             assert response.removedCmHandles.size() == 1
376             with(response.removedCmHandles[0]) {
377                 assert it.status == Status.FAILURE
378                 assert it.cmHandle == 'cmhandle'
379                 assert it.errorText == 'Failed'
380                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
381             }
382     }
383
384     def 'Remove CmHandle Error Handling: #scenario'() {
385         given: 'a registration'
386             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
387                 removedCmHandles: ['cmhandle'])
388         and: 'cm-handle deletion fails on batch'
389             mockInventoryPersistence.deleteDataNodes(_) >> { throw deleteListElementException }
390         and: 'cm-handle deletion fails on individual delete'
391             mockInventoryPersistence.deleteDataNode(_) >> { throw deleteListElementException }
392         when: 'registration is updated to delete cmhandle'
393             def response = objectUnderTest.updateDmiRegistration(dmiPluginRegistration)
394         then: 'a failure response is received'
395             assert response.removedCmHandles.size() == 1
396             with(response.removedCmHandles[0]) {
397                 assert it.status == Status.FAILURE
398                 assert it.cmHandle == 'cmhandle'
399                 assert it.ncmpResponseStatus == expectedError
400                 assert it.errorText == expectedErrorText
401             }
402         and: 'the cm handle state is not updated to "DELETED"'
403             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_, CmHandleState.DELETED)
404         where:
405         scenario                     | deleteListElementException                || expectedError        | expectedErrorText
406         'cm-handle does not exist'   | new DataNodeNotFoundException('', '', '') || CM_HANDLES_NOT_FOUND | 'cm handle reference(s) not found'
407         'cm-handle has invalid name' | new DataValidationException('', '')       || CM_HANDLE_INVALID_ID | 'cm handle reference has an invalid character(s) in id'
408         'an unexpected exception'    | new RuntimeException('Failed')            || UNKNOWN_ERROR        | 'Failed'
409     }
410
411     def 'Set Cm Handle Data Sync Enabled Flag where data sync flag is  #scenario'() {
412         given: 'an existing cm handle composite state'
413             def compositeState = new CompositeState(cmHandleState: CmHandleState.READY, dataSyncEnabled: initialDataSyncEnabledFlag,
414                 dataStores: CompositeState.DataStores.builder()
415                     .operationalDataStore(CompositeState.Operational.builder()
416                         .dataStoreSyncState(initialDataSyncState)
417                         .build()).build())
418         and: 'get cm handle state returns the composite state for the given cm handle id'
419             mockInventoryPersistence.getCmHandleState('some-cm-handle-id') >> compositeState
420         when: 'set data sync enabled is called with the data sync enabled flag set to #dataSyncEnabledFlag'
421             objectUnderTest.setDataSyncEnabled('some-cm-handle-id', dataSyncEnabledFlag)
422         then: 'the data sync enabled flag is set to #dataSyncEnabled'
423             compositeState.dataSyncEnabled == dataSyncEnabledFlag
424         and: 'the data store sync state is set to #expectedDataStoreSyncState'
425             compositeState.dataStores.operationalDataStore.dataStoreSyncState == expectedDataStoreSyncState
426         and: 'the cps data service to delete data nodes is invoked the expected number of times'
427             deleteDataNodeExpectedNumberOfInvocation * mockCpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, 'some-cm-handle-id', '/netconf-state', _)
428         and: 'the inventory persistence service to update node leaves is called with the correct values'
429             saveCmHandleStateExpectedNumberOfInvocations * mockInventoryPersistence.saveCmHandleState('some-cm-handle-id', compositeState)
430         where: 'the following data sync enabled flag is used'
431             scenario                                              | dataSyncEnabledFlag | initialDataSyncEnabledFlag | initialDataSyncState               || expectedDataStoreSyncState         | deleteDataNodeExpectedNumberOfInvocation | saveCmHandleStateExpectedNumberOfInvocations
432             'enabled'                                             | true                | false                      | DataStoreSyncState.NONE_REQUESTED || DataStoreSyncState.UNSYNCHRONIZED | 0 | 1
433             'disabled'                                            | false               | true                       | DataStoreSyncState.UNSYNCHRONIZED  || DataStoreSyncState.NONE_REQUESTED  | 0                                        | 1
434             'disabled where sync-state is currently SYNCHRONIZED' | false               | true                       | DataStoreSyncState.SYNCHRONIZED    || DataStoreSyncState.NONE_REQUESTED  | 1                                        | 1
435             'is set to existing flag state'                       | true                | true                       | DataStoreSyncState.UNSYNCHRONIZED  || DataStoreSyncState.UNSYNCHRONIZED  | 0                                        | 0
436     }
437
438     def 'Set cm Handle Data Sync Enabled flag with following cm handle not in ready state exception' () {
439         given: 'a cm handle composite state'
440             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED, dataSyncEnabled: false)
441         and: 'get cm handle state returns the composite state for the given cm handle id'
442             mockInventoryPersistence.getCmHandleState('some-cm-handle-id') >> compositeState
443         when: 'set data sync enabled is called with the data sync enabled flag set to true'
444             objectUnderTest.setDataSyncEnabled('some-cm-handle-id', true)
445         then: 'the expected exception is thrown'
446             thrown(CpsException)
447         and: 'the inventory persistence service to update node leaves is not invoked'
448             0 * mockInventoryPersistence.saveCmHandleState(_, _)
449     }
450
451
452
453 }