Remove the dependency-cycle between beans
[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                         def yangModelCmHandles = args[0]
215                         assert yangModelCmHandles.id == ['cmhandle']
216                         assert yangModelCmHandles.dmiServiceName == ['my-server']
217                     }
218             }
219         where:
220             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
221             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
222             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || [:]                                        | '[{"name":"public-key","value":"public-value"}]'
223             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | [:]
224             'without dmi & public properties' | [:]                      | [:]                            || [:]                                        | [:]
225     }
226
227     def 'Add CM-Handle to trustLevelPerCmHandle Successfully with: #scenario.'() {
228         given: 'a registration with trustLevel and populated cache'
229             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
230             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'ch-1', registrationTrustLevel: TrustLevel.NONE),
231                                                       new NcmpServiceCmHandle(cmHandleId: cmHandleId, registrationTrustLevel: registrationTrustLevel)]
232         when: 'registration is updated'
233             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
234         then: 'a successful response is received'
235             assert response.createdCmHandles.size() == expectedNumberOfCreatedCmHandles
236         and: 'trustLevel is set for the created cm-handle'
237             1 * mockTrustLevelManager.handleInitialRegistrationOfTrustLevels(_)
238         where:
239             scenario                                 | cmHandleId | registrationTrustLevel || expectedNumberOfCreatedCmHandles
240             'new trusted cm handle'                  | 'ch-new'   | TrustLevel.COMPLETE    || 2
241             'existing cm handle without trust level' | 'ch-1'     | null                   || 1
242             'new cm handle without trust level'      | 'ch-new'   | null                   || 2
243     }
244
245     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
246         given: 'a registration with three cm-handles to be created'
247             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
248                     createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
249                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
250                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
251         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
252             def xpath = "somePathWithId[@id='cmhandle2']"
253             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw AlreadyDefinedException.forDataNodes([xpath], 'some-context') }
254         when: 'registration is updated to create cm-handles'
255             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
256         then: 'a response is received for all cm-handles'
257             response.createdCmHandles.size() == 1
258         and: 'all cm-handles creation fails'
259             response.createdCmHandles.each {
260                 assert it.cmHandle == 'cmhandle2'
261                 assert it.status == Status.FAILURE
262                 assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
263                 assert it.errorText == 'cm-handle already exists'
264             }
265     }
266
267     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
268         given: 'a registration without cm-handle properties'
269             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
270             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
271         and: 'cm-handler registration fails: #scenario'
272             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw exception }
273         when: 'registration is updated'
274             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
275         then: 'a failure response is received'
276             response.createdCmHandles.size() == 1
277             with(response.createdCmHandles[0]) {
278                 assert it.status == Status.FAILURE
279                 assert it.cmHandle ==  'cmhandle'
280                 assert it.ncmpResponseStatus == expectedError
281                 assert it.errorText == expectedErrorText
282             }
283         where:
284             scenario                                        | exception                                                                      || expectedError           | expectedErrorText
285             'cm-handle already exist'                       | AlreadyDefinedException.forDataNodes(["path[@id='cmhandle']"], 'some-context') || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
286             'unknown exception while registering cm-handle' | new RuntimeException('Failed')                                                 || UNKNOWN_ERROR           | 'Failed'
287     }
288
289     def 'Update CM-Handle: Update Operation Response is added to the response'() {
290         given: 'a registration to update CmHandles'
291             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', updatedCmHandles: [{}])
292         and: 'cm-handle updates can be processed successfully'
293             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
294                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
295                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLES_NOT_FOUND),
296                                            CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
297             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
298         when: 'registration is updated'
299             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
300         then: 'the response contains updateOperationResponse'
301             assert response.updatedCmHandles.size() == 4
302             assert response.updatedCmHandles.containsAll(updateOperationResponse)
303     }
304
305     def 'Remove CmHandle Successfully: #scenario'() {
306         given: 'a registration'
307             addPersistedYangModelCmHandles(['cmhandle'])
308             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
309                 removedCmHandles: ['cmhandle'])
310         and: '#scenario'
311             mockCpsModuleService.deleteSchemaSetsWithCascade(_, ['cmhandle']) >>
312                 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
313         when: 'registration is updated to delete cmhandle'
314             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
315         then: 'the cmHandle state is updated to "DELETING"'
316             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
317         and: 'method to delete relevant schema set is called once'
318             1 * mockInventoryPersistence.deleteSchemaSetsWithCascade(_)
319         and: 'method to delete relevant list/list element is called once'
320             1 * mockInventoryPersistence.deleteDataNodes(_)
321         and: 'successful response is received'
322             assert response.removedCmHandles.size() == 1
323             with(response.removedCmHandles[0]) {
324                 assert it.status == Status.SUCCESS
325                 assert it.cmHandle == 'cmhandle'
326             }
327         and: 'the cmHandle state is updated to "DELETED"'
328             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
329         where:
330             scenario                                            | schemaSetExist
331             'schema-set exists and can be deleted successfully' | true
332             'schema-set does not exist'                         | false
333     }
334
335     def 'Remove CmHandle: Partial Success'() {
336         given: 'some unique yang model cm handles'
337             addPersistedYangModelCmHandles(['cmhandle1', 'cmhandle2', 'cmhandle3'])
338         and: 'a registration with three cm-handles to be deleted'
339             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
340                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
341         and: 'cm-handle deletion fails on batch'
342             mockInventoryPersistence.deleteDataNodes(_) >> { throw new RuntimeException("Failed") }
343         and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
344             mockInventoryPersistence.deleteDataNode("/dmi-registry/cm-handles[@id='cmhandle2']") >> { throw new RuntimeException("Failed") }
345         when: 'registration is updated to delete cmhandles'
346             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
347         then: 'the cmHandle states are all updated to "DELETING"'
348             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({ assert it.every { entry -> entry.value == CmHandleState.DELETING } })
349         and: 'a response is received for all cm-handles'
350             response.removedCmHandles.size() == 3
351         and: 'successfully de-registered cm handle 1 is removed from in progress map'
352             1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle1')
353         and: 'successfully de-registered cm handle 3 is removed from in progress map even though it was already being removed'
354             1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle3') >> 'already in progress'
355         and: 'failed de-registered cm handle entries should not be removed from in progress map'
356             0 * mockModuleSyncStartedOnCmHandles.remove('cmhandle2')
357         and: '1st and 3rd cm-handle deletes successfully'
358             with(response.removedCmHandles[0]) {
359                 assert it.status == Status.SUCCESS
360                 assert it.cmHandle == 'cmhandle1'
361             }
362             with(response.removedCmHandles[2]) {
363                 assert it.status == Status.SUCCESS
364                 assert it.cmHandle == 'cmhandle3'
365             }
366         and: '2nd cm-handle deletion fails'
367             with(response.removedCmHandles[1]) {
368                 assert it.status == Status.FAILURE
369                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
370                 assert it.errorText == 'Failed'
371                 assert it.cmHandle == 'cmhandle2'
372             }
373         and: 'the cmHandle state is updated to DELETED for 1st and 3rd'
374             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({
375                 assert it.size() == 2
376                 assert it.every { entry -> entry.value == CmHandleState.DELETED }
377             })
378     }
379
380     def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
381         given: 'a registration'
382             addPersistedYangModelCmHandles(['cmhandle'])
383             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
384                 removedCmHandles: ['cmhandle'])
385         and: 'schema set batch deletion failed with unknown error'
386             mockInventoryPersistence.deleteSchemaSetsWithCascade(_) >> { throw new RuntimeException('Failed') }
387         and: 'schema set single deletion failed with unknown error'
388             mockInventoryPersistence.deleteSchemaSetWithCascade(_) >> { throw new RuntimeException('Failed') }
389         when: 'registration is updated to delete cmhandle'
390             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
391         then: 'no exception is thrown'
392             noExceptionThrown()
393         and: 'cm-handle is not deleted'
394             0 * mockInventoryPersistence.deleteDataNodes(_)
395         and: 'the cmHandle state is not updated to "DELETED"'
396             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch([yangModelCmHandle: CmHandleState.DELETED])
397         and: 'a failure response is received'
398             assert response.removedCmHandles.size() == 1
399             with(response.removedCmHandles[0]) {
400                 assert it.status == Status.FAILURE
401                 assert it.cmHandle == 'cmhandle'
402                 assert it.errorText == 'Failed'
403                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
404             }
405     }
406
407     def 'Remove CmHandle Error Handling: #scenario'() {
408         given: 'a registration'
409             addPersistedYangModelCmHandles(['cmhandle'])
410             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
411                 removedCmHandles: ['cmhandle'])
412         and: 'cm-handle deletion fails on batch'
413             mockInventoryPersistence.deleteDataNodes(_) >> { throw deleteListElementException }
414         and: 'cm-handle deletion fails on individual delete'
415             mockInventoryPersistence.deleteDataNode(_) >> { throw deleteListElementException }
416         when: 'registration is updated to delete cmhandle'
417             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
418         then: 'a failure response is received'
419             assert response.removedCmHandles.size() == 1
420             with(response.removedCmHandles[0]) {
421                 assert it.status == Status.FAILURE
422                 assert it.cmHandle == 'cmhandle'
423                 assert it.ncmpResponseStatus == expectedError
424                 assert it.errorText == expectedErrorText
425             }
426         and: 'the cm handle state is not updated to "DELETED"'
427             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_, CmHandleState.DELETED)
428         where:
429         scenario                     | cmHandleId             | deleteListElementException                || expectedError        | expectedErrorText
430         'cm-handle does not exist'   | 'cmhandle'             | new DataNodeNotFoundException('', '', '') || CM_HANDLES_NOT_FOUND | 'cm handle id(s) not found'
431         'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException('', '')       || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
432         'an unexpected exception'    | 'cmhandle'             | new RuntimeException('Failed')            || UNKNOWN_ERROR        | 'Failed'
433     }
434
435     def getObjectUnderTest() {
436         return Spy(new NetworkCmProxyDataServiceImpl(spiedJsonObjectMapper, mockDmiDataOperations,
437                 mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCmHandleQueries,
438                 stubbedNetworkCmProxyCmHandlerQueryService, mockLcmEventsCmHandleStateHandler, mockCpsDataService,
439                 mockModuleSyncStartedOnCmHandles, trustLevelPerDmiPlugin, mockTrustLevelManager))
440     }
441
442     def addPersistedYangModelCmHandles(ids) {
443         def yangModelCmHandles = ids.collect { new YangModelCmHandle(id:it) }
444         mockInventoryPersistence.getYangModelCmHandles(ids) >> yangModelCmHandles
445     }
446 }