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