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