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