Merge "Add integration test for extending API: Get Module Definitions"
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImplRegistrationSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl
23
24 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
25 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST
27 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
28 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
29
30 import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevelManager
31 import org.onap.cps.ncmp.api.impl.utils.CmHandleIdMapper
32 import org.onap.cps.ncmp.api.models.UpgradedCmHandles
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.Specification
55
56 class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification {
57
58     def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
59     def mockCpsModuleService = Mock(CpsModuleService)
60     def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
61     def mockDmiDataOperations = Mock(DmiDataOperations)
62     def mockNetworkCmProxyDataServicePropertyHandler = Mock(NetworkCmProxyDataServicePropertyHandler)
63     def mockInventoryPersistence = Mock(InventoryPersistence)
64     def mockCmHandleQueries = Mock(CmHandleQueries)
65     def stubbedNetworkCmProxyCmHandlerQueryService = Stub(NetworkCmProxyCmHandleQueryService)
66     def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
67     def mockCpsDataService = Mock(CpsDataService)
68     def mockModuleSyncStartedOnCmHandles = Mock(IMap<String, Object>)
69     def trustLevelPerDmiPlugin = [:]
70     def mockTrustLevelManager = Mock(TrustLevelManager)
71     def mockCmHandleIdMapper = Mock(CmHandleIdMapper)
72     def objectUnderTest = getObjectUnderTest()
73     def mockModuleSetTagCache = [:]
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             2 * 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.initiateStateAdvised(_) >> {
212                 args ->  {
213                         def yangModelCmHandles = args[0]
214                         assert yangModelCmHandles.id == ['cmhandle']
215                         assert yangModelCmHandles.dmiServiceName == ['my-server']
216                     }
217             }
218         where:
219             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
220             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
221             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || [:]                                        | '[{"name":"public-key","value":"public-value"}]'
222             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | [:]
223             'without dmi & public properties' | [:]                      | [:]                            || [:]                                        | [:]
224     }
225
226     def 'Add CM-Handle to trustLevelPerCmHandle Successfully with: #scenario.'() {
227         given: 'a registration with trustLevel and populated cache'
228             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
229             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'ch-1', registrationTrustLevel: TrustLevel.NONE),
230                                                       new NcmpServiceCmHandle(cmHandleId: cmHandleId, registrationTrustLevel: registrationTrustLevel)]
231         when: 'registration is updated'
232             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
233         then: 'a successful response is received'
234             assert response.createdCmHandles.size() == expectedNumberOfCreatedCmHandles
235         and: 'trustLevel is set for the created cm-handle'
236             1 * mockTrustLevelManager.handleInitialRegistrationOfTrustLevels(_)
237         where:
238             scenario                                 | cmHandleId | registrationTrustLevel || expectedNumberOfCreatedCmHandles
239             'new trusted cm handle'                  | 'ch-new'   | TrustLevel.COMPLETE    || 2
240             'existing cm handle without trust level' | 'ch-1'     | null                   || 1
241             'new cm handle without trust level'      | 'ch-new'   | null                   || 2
242     }
243
244     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
245         given: 'a registration with three cm-handles to be created'
246             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
247                     createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
248                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
249                                        new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
250         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
251             def xpath = "somePathWithId[@id='cmhandle2']"
252             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw AlreadyDefinedException.forDataNodes([xpath], 'some-context') }
253         when: 'registration is updated to create cm-handles'
254             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
255         then: 'a response is received for all cm-handles'
256             response.createdCmHandles.size() == 1
257         and: 'all cm-handles creation fails'
258             response.createdCmHandles.each {
259                 assert it.cmHandle == 'cmhandle2'
260                 assert it.status == Status.FAILURE
261                 assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
262                 assert it.errorText == 'cm-handle already exists'
263             }
264     }
265
266     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
267         given: 'a registration without cm-handle properties'
268             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
269             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
270         and: 'cm-handler registration fails: #scenario'
271             mockLcmEventsCmHandleStateHandler.initiateStateAdvised(*_) >> { throw exception }
272         when: 'registration is updated'
273             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
274         then: 'a failure response is received'
275             response.createdCmHandles.size() == 1
276             with(response.createdCmHandles[0]) {
277                 assert it.status == Status.FAILURE
278                 assert it.cmHandle ==  'cmhandle'
279                 assert it.ncmpResponseStatus == expectedError
280                 assert it.errorText == expectedErrorText
281             }
282         where:
283             scenario                                        | exception                                                                      || expectedError           | expectedErrorText
284             'cm-handle already exist'                       | AlreadyDefinedException.forDataNodes(["path[@id='cmhandle']"], 'some-context') || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
285             'unknown exception while registering cm-handle' | new RuntimeException('Failed')                                                 || UNKNOWN_ERROR           | 'Failed'
286     }
287
288     def 'Update CM-Handle: Update Operation Response is added to the response'() {
289         given: 'a registration to update CmHandles'
290             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', updatedCmHandles: [{}])
291         and: 'cm-handle updates can be processed successfully'
292             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
293                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
294                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLES_NOT_FOUND),
295                                            CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
296             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
297         when: 'registration is updated'
298             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
299         then: 'the response contains updateOperationResponse'
300             assert response.updatedCmHandles.size() == 4
301             assert response.updatedCmHandles.containsAll(updateOperationResponse)
302     }
303
304     def 'Remove CmHandle Successfully: #scenario'() {
305         given: 'a registration'
306             addPersistedYangModelCmHandles(['cmhandle'])
307             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
308                 removedCmHandles: ['cmhandle'])
309         and: '#scenario'
310             mockCpsModuleService.deleteSchemaSetsWithCascade(_, ['cmhandle']) >>
311                 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
312         when: 'registration is updated to delete cmhandle'
313             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
314         then: 'the cmHandle state is updated to "DELETING"'
315             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
316         and: 'method to delete relevant schema set is called once'
317             1 * mockInventoryPersistence.deleteSchemaSetsWithCascade(_)
318         and: 'method to delete relevant list/list element is called once'
319             1 * mockInventoryPersistence.deleteDataNodes(_)
320         and: 'successful response is received'
321             assert response.removedCmHandles.size() == 1
322             with(response.removedCmHandles[0]) {
323                 assert it.status == Status.SUCCESS
324                 assert it.cmHandle == 'cmhandle'
325             }
326         and: 'the cmHandle state is updated to "DELETED"'
327             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
328         where:
329             scenario                                            | schemaSetExist
330             'schema-set exists and can be deleted successfully' | true
331             'schema-set does not exist'                         | false
332     }
333
334     def 'Remove CmHandle: Partial Success'() {
335         given: 'some unique yang model cm handles'
336             addPersistedYangModelCmHandles(['cmhandle1', 'cmhandle2', 'cmhandle3'])
337         and: 'a registration with three cm-handles to be deleted'
338             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
339                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
340         and: 'cm-handle deletion fails on batch'
341             mockInventoryPersistence.deleteDataNodes(_) >> { throw new RuntimeException("Failed") }
342         and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
343             mockInventoryPersistence.deleteDataNode("/dmi-registry/cm-handles[@id='cmhandle2']") >> { throw new RuntimeException("Failed") }
344         when: 'registration is updated to delete cmhandles'
345             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
346         then: 'the cmHandle states are all updated to "DELETING"'
347             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({ assert it.every { entry -> entry.value == CmHandleState.DELETING } })
348         and: 'a response is received for all cm-handles'
349             response.removedCmHandles.size() == 3
350         and: 'successfully de-registered cm handle 1 is removed from in progress map'
351             1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle1')
352         and: 'successfully de-registered cm handle 3 is removed from in progress map even though it was already being removed'
353             1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle3') >> 'already in progress'
354         and: 'failed de-registered cm handle entries should not be removed from in progress map'
355             0 * mockModuleSyncStartedOnCmHandles.remove('cmhandle2')
356         and: '1st and 3rd cm-handle deletes successfully'
357             with(response.removedCmHandles[0]) {
358                 assert it.status == Status.SUCCESS
359                 assert it.cmHandle == 'cmhandle1'
360             }
361             with(response.removedCmHandles[2]) {
362                 assert it.status == Status.SUCCESS
363                 assert it.cmHandle == 'cmhandle3'
364             }
365         and: '2nd cm-handle deletion fails'
366             with(response.removedCmHandles[1]) {
367                 assert it.status == Status.FAILURE
368                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
369                 assert it.errorText == 'Failed'
370                 assert it.cmHandle == 'cmhandle2'
371             }
372         and: 'the cmHandle state is updated to DELETED for 1st and 3rd'
373             1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({
374                 assert it.size() == 2
375                 assert it.every { entry -> entry.value == CmHandleState.DELETED }
376             })
377     }
378
379     def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
380         given: 'a registration'
381             addPersistedYangModelCmHandles(['cmhandle'])
382             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
383                 removedCmHandles: ['cmhandle'])
384         and: 'schema set batch deletion failed with unknown error'
385             mockInventoryPersistence.deleteSchemaSetsWithCascade(_) >> { throw new RuntimeException('Failed') }
386         and: 'schema set single deletion failed with unknown error'
387             mockInventoryPersistence.deleteSchemaSetWithCascade(_) >> { throw new RuntimeException('Failed') }
388         when: 'registration is updated to delete cmhandle'
389             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
390         then: 'no exception is thrown'
391             noExceptionThrown()
392         and: 'cm-handle is not deleted'
393             0 * mockInventoryPersistence.deleteDataNodes(_)
394         and: 'the cmHandle state is not updated to "DELETED"'
395             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch([yangModelCmHandle: CmHandleState.DELETED])
396         and: 'a failure response is received'
397             assert response.removedCmHandles.size() == 1
398             with(response.removedCmHandles[0]) {
399                 assert it.status == Status.FAILURE
400                 assert it.cmHandle == 'cmhandle'
401                 assert it.errorText == 'Failed'
402                 assert it.ncmpResponseStatus == UNKNOWN_ERROR
403             }
404     }
405
406     def 'Remove CmHandle Error Handling: #scenario'() {
407         given: 'a registration'
408             addPersistedYangModelCmHandles(['cmhandle'])
409             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
410                 removedCmHandles: ['cmhandle'])
411         and: 'cm-handle deletion fails on batch'
412             mockInventoryPersistence.deleteDataNodes(_) >> { throw deleteListElementException }
413         and: 'cm-handle deletion fails on individual delete'
414             mockInventoryPersistence.deleteDataNode(_) >> { throw deleteListElementException }
415         when: 'registration is updated to delete cmhandle'
416             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
417         then: 'a failure response is received'
418             assert response.removedCmHandles.size() == 1
419             with(response.removedCmHandles[0]) {
420                 assert it.status == Status.FAILURE
421                 assert it.cmHandle == 'cmhandle'
422                 assert it.ncmpResponseStatus == expectedError
423                 assert it.errorText == expectedErrorText
424             }
425         and: 'the cm handle state is not updated to "DELETED"'
426             0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_, CmHandleState.DELETED)
427         where:
428         scenario                     | cmHandleId             | deleteListElementException                || expectedError        | expectedErrorText
429         'cm-handle does not exist'   | 'cmhandle'             | new DataNodeNotFoundException('', '', '') || CM_HANDLES_NOT_FOUND | 'cm handle id(s) not found'
430         'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException('', '')       || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
431         'an unexpected exception'    | 'cmhandle'             | new RuntimeException('Failed')            || UNKNOWN_ERROR        | 'Failed'
432     }
433
434     def 'Adding data to alternate id caches.'() {
435         given: 'a registration with three CM Handles to be created'
436             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
437                     createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1', alternateId: 'my-alternate-id-1')])
438         when: 'the DMI plugin registration happens'
439             objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
440         then: 'the new alternate id is added to the cache'
441             1 * mockCmHandleIdMapper.addMapping('cmhandle1', 'my-alternate-id-1')
442     }
443
444     def getObjectUnderTest() {
445         return Spy(new NetworkCmProxyDataServiceImpl(spiedJsonObjectMapper, mockDmiDataOperations,
446                 mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCmHandleQueries,
447                 stubbedNetworkCmProxyCmHandlerQueryService, mockLcmEventsCmHandleStateHandler, mockCpsDataService,
448                 mockModuleSyncStartedOnCmHandles, trustLevelPerDmiPlugin, mockTrustLevelManager, mockCmHandleIdMapper, mockModuleSetTagCache))
449     }
450
451     def addPersistedYangModelCmHandles(ids) {
452         def yangModelCmHandles = ids.collect { new YangModelCmHandle(id:it) }
453         mockInventoryPersistence.getYangModelCmHandles(ids) >> yangModelCmHandles
454     }
455 }