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
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 com.fasterxml.jackson.databind.ObjectMapper
25 import com.hazelcast.map.IMap
26 import org.onap.cps.api.CpsDataService
27 import org.onap.cps.api.CpsModuleService
28 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandlerQueryService
29 import org.onap.cps.ncmp.api.impl.event.lcm.LcmEventsCmHandleStateHandler
30 import org.onap.cps.ncmp.api.impl.exception.DmiRequestException
31 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations
32 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
33 import org.onap.cps.ncmp.api.inventory.CmHandleQueries
34 import org.onap.cps.ncmp.api.inventory.CmHandleState
35 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
36 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse
37 import org.onap.cps.ncmp.api.models.DmiPluginRegistration
38 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
39 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch
40 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
41 import org.onap.cps.spi.exceptions.DataValidationException
42 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
43 import org.onap.cps.utils.JsonObjectMapper
44 import spock.lang.Shared
45 import spock.lang.Specification
47 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
48 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_ALREADY_EXIST
49 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_INVALID_ID
50 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
51 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
52 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED
54 class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification {
57 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(NetworkCmProxyCmHandlerQueryService)
66 def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
67 def mockCpsDataService = Mock(CpsDataService)
68 def mockModuleSyncStartedOnCmHandles = Mock(IMap<String, Object>)
69 def objectUnderTest = getObjectUnderTest()
71 def 'DMI Registration: Create, Update & Delete operations are processed in the right order'() {
72 given: 'a registration with operations of all three types'
73 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
74 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
75 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
76 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
77 and: 'cm handles are persisted'
78 mockInventoryPersistence.getYangModelCmHandles(['cmhandle-2']) >> [new YangModelCmHandle()]
79 when: 'registration is processed'
80 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
81 then: 'cm-handles are removed first'
82 1 * objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_)
83 and: 'de-registered cm handle entry is removed from in progress map'
84 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle-2')
85 then: 'cm-handles are created'
86 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_)
87 then: 'cm-handles are updated'
88 1 * mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_)
91 def 'DMI Registration: Response from all operations types are in response'() {
92 given: 'a registration with operations of all three types'
93 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
94 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
95 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
96 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
97 and: 'update cm-handles can be processed successfully'
98 def updateResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-2')]
99 mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_) >> updateResponses
100 and: 'create cm-handles can be processed successfully'
101 def createdResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-1')]
102 objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_) >> createdResponses
103 and: 'delete cm-handles can be processed successfully'
104 def removeResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-3')]
105 objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_) >> removeResponses
106 when: 'registration is processed'
107 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
108 then: 'response has values from all operations'
109 response.removedCmHandles == removeResponses
110 response.createdCmHandles == createdResponses
111 response.updatedCmHandles == updateResponses
114 def 'Create CM-handle Validation: Registration with valid Service names: #scenario'() {
115 given: 'a registration '
116 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
117 dmiDataPlugin: dmiDataPlugin)
118 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
119 when: 'update registration and sync module is called with correct DMI plugin information'
120 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
121 then: 'create cm handles registration and sync modules is called with the correct plugin information'
122 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
124 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin
125 'combined DMI plugin' | 'service1' | '' | ''
126 'data & model DMI plugins' | '' | 'service1' | 'service2'
127 'data & model using same service' | '' | 'service1' | 'service1'
130 def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
131 given: 'a registration '
132 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
133 dmiDataPlugin: dmiDataPlugin)
134 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
135 when: 'registration is called with incorrect DMI plugin information'
136 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
137 then: 'a DMI Request Exception is thrown with correct message details'
138 def exceptionThrown = thrown(DmiRequestException.class)
139 assert exceptionThrown.getMessage().contains(expectedMessageDetails)
140 and: 'registration is not called'
141 0 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
143 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
144 'empty DMI plugins' | '' | '' | '' || 'No DMI plugin service names'
145 'blank DMI plugins' | ' ' | ' ' | ' ' || 'No DMI plugin service names'
146 'null DMI plugins' | null | null | null || 'No DMI plugin service names'
147 'all DMI plugins' | 'service1' | 'service2' | 'service3' || 'Cannot register combined plugin service name and other service names'
148 '(combined)DMI and Data Plugin' | 'service1' | '' | 'service2' || 'Cannot register combined plugin service name and other service names'
149 '(combined)DMI and model Plugin' | 'service1' | 'service2' | '' || 'Cannot register combined plugin service name and other service names'
150 'only model DMI plugin' | '' | 'service1' | '' || 'Cannot register just a Data or Model plugin service name'
151 'only data DMI plugin' | '' | '' | 'service1' || 'Cannot register just a Data or Model plugin service name'
154 def 'Create CM-Handle Successfully: #scenario.'() {
155 given: 'a registration without cm-handle properties'
156 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
157 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
158 when: 'registration is updated'
159 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
160 then: 'a successful response is received'
161 response.createdCmHandles.size() == 1
162 with(response.createdCmHandles[0]) {
163 assert it.status == Status.SUCCESS
164 assert it.cmHandle == 'cmhandle'
166 and: 'state handler is invoked with the expected parameters'
167 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> {
170 def cmHandleStatePerCmHandle = (args[0] as Map)
171 cmHandleStatePerCmHandle.each {
172 assert (it.key.id == 'cmhandle'
173 && it.key.dmiServiceName == 'my-server'
174 && it.value == CmHandleState.ADVISED)
179 scenario | dmiProperties | publicProperties || expectedDmiProperties | expectedPublicProperties
180 'with dmi & public properties' | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
181 'with only public properties' | [:] | ['public-key': 'public-value'] || '[]' | '[{"name":"public-key","value":"public-value"}]'
182 'with only dmi properties' | ['dmi-key': 'dmi-value'] | [:] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[]'
183 'without dmi & public properties' | [:] | [:] || '[]' | '[]'
186 def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
187 given: 'a registration with three cm-handles to be created'
188 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
189 createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
190 new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
191 new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
192 and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
193 def xpath = "somePathWithId[@id='cmhandle2']"
194 mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(*_) >> { throw new AlreadyDefinedExceptionBatch([xpath]) }
195 when: 'registration is updated to create cm-handles'
196 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
197 then: 'a response is received for all cm-handles'
198 response.createdCmHandles.size() == 1
199 and: 'all cm-handles creation fails'
200 response.createdCmHandles.each {
201 assert it.cmHandle == 'cmhandle2'
202 assert it.status == Status.FAILURE
203 assert it.registrationError == CM_HANDLE_ALREADY_EXIST
204 assert it.errorText == 'cm-handle already exists'
208 def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
209 given: 'a registration without cm-handle properties'
210 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
211 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
212 and: 'cm-handler registration fails: #scenario'
213 mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(*_) >> { throw exception }
214 when: 'registration is updated'
215 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
216 then: 'a failure response is received'
217 response.createdCmHandles.size() == 1
218 with(response.createdCmHandles[0]) {
219 assert it.status == Status.FAILURE
220 assert it.cmHandle == 'cmhandle'
221 assert it.registrationError == expectedError
222 assert it.errorText == expectedErrorText
225 scenario | exception || expectedError | expectedErrorText
226 'cm-handle already exist' | new AlreadyDefinedExceptionBatch(["'path[@id='cmhandle']".toString()]) || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
227 'unknown exception while registering cm-handle' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
230 def 'Update CM-Handle: Update Operation Response is added to the response'() {
231 given: 'a registration to update CmHandles'
232 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server', updatedCmHandles: [{}])
233 and: 'cm-handle updates can be processed successfully'
234 def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
235 CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
236 CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLE_DOES_NOT_EXIST),
237 CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
238 mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
239 when: 'registration is updated'
240 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
241 then: 'the response contains updateOperationResponse'
242 assert response.updatedCmHandles.size() == 4
243 assert response.updatedCmHandles.containsAll(updateOperationResponse)
246 def 'Remove CmHandle Successfully: #scenario'() {
247 given: 'a registration'
248 addPersistedYangModelCmHandles(['cmhandle'])
249 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
250 removedCmHandles: ['cmhandle'])
252 mockCpsModuleService.deleteSchemaSet(_, 'cmhandle', CASCADE_DELETE_ALLOWED) >>
253 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
254 when: 'registration is updated to delete cmhandle'
255 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
256 then: 'the cmHandle state is updated to "DELETING"'
257 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
258 and: 'method to delete relevant schema set is called once'
259 1 * mockInventoryPersistence.deleteSchemaSetWithCascade(_)
260 and: 'method to delete relevant list/list element is called once'
261 1 * mockInventoryPersistence.deleteDataNodes(_)
262 and: 'successful response is received'
263 assert response.removedCmHandles.size() == 1
264 with(response.removedCmHandles[0]) {
265 assert it.status == Status.SUCCESS
266 assert it.cmHandle == 'cmhandle'
268 and: 'the cmHandle state is updated to "DELETED"'
269 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_)
271 scenario | schemaSetExist
272 'schema-set exists and can be deleted successfully' | true
273 'schema-set does not exist' | false
276 def 'Remove CmHandle: Partial Success'() {
277 given: 'some unique yang model cm handles'
278 addPersistedYangModelCmHandles(['cmhandle1', 'cmhandle2', 'cmhandle3'])
279 and: 'a registration with three cm-handles to be deleted'
280 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
281 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
282 and: 'cm-handle deletion fails on batch'
283 mockInventoryPersistence.deleteDataNodes(_) >> { throw new RuntimeException("Failed") }
284 and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
285 mockInventoryPersistence.deleteDataNode("/dmi-registry/cm-handles[@id='cmhandle2']") >> { throw new RuntimeException("Failed") }
286 when: 'registration is updated to delete cmhandles'
287 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
288 then: 'the cmHandle states are all updated to "DELETING"'
289 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({ assert it.every { entry -> entry.value == CmHandleState.DELETING } })
290 and: 'a response is received for all cm-handles'
291 response.removedCmHandles.size() == 3
292 and: 'successfully de-registered cm handle entries are removed from in progress map'
293 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle1')
294 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle3')
295 and: 'failed de-registered cm handle entries should not be removed from in progress map'
296 0 * mockModuleSyncStartedOnCmHandles.remove('cmhandle2')
297 and: '1st and 3rd cm-handle deletes successfully'
298 with(response.removedCmHandles[0]) {
299 assert it.status == Status.SUCCESS
300 assert it.cmHandle == 'cmhandle1'
302 with(response.removedCmHandles[2]) {
303 assert it.status == Status.SUCCESS
304 assert it.cmHandle == 'cmhandle3'
306 and: '2nd cm-handle deletion fails'
307 with(response.removedCmHandles[1]) {
308 assert it.status == Status.FAILURE
309 assert it.registrationError == UNKNOWN_ERROR
310 assert it.errorText == 'Failed'
311 assert it.cmHandle == 'cmhandle2'
313 and: 'the cmHandle state is updated to DELETED for 1st and 3rd'
314 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch({
315 assert it.size() == 2
316 assert it.every { entry -> entry.value == CmHandleState.DELETED }
320 def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
321 given: 'a registration'
322 addPersistedYangModelCmHandles(['cmhandle'])
323 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
324 removedCmHandles: ['cmhandle'])
325 and: 'schema set deletion failed with unknown error'
326 mockInventoryPersistence.deleteSchemaSetWithCascade(_) >> { throw new RuntimeException('Failed') }
327 when: 'registration is updated to delete cmhandle'
328 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
329 then: 'no exception is thrown'
331 and: 'cm-handle is not deleted'
332 0 * mockInventoryPersistence.deleteDataNodes(_)
333 and: 'the cmHandle state is not updated to "DELETED"'
334 0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch([yangModelCmHandle: CmHandleState.DELETED])
335 and: 'a failure response is received'
336 assert response.removedCmHandles.size() == 1
337 with(response.removedCmHandles[0]) {
338 assert it.status == Status.FAILURE
339 assert it.cmHandle == 'cmhandle'
340 assert it.errorText == 'Failed'
341 assert it.registrationError == UNKNOWN_ERROR
345 def 'Remove CmHandle Error Handling: #scenario'() {
346 given: 'a registration'
347 addPersistedYangModelCmHandles(['cmhandle'])
348 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
349 removedCmHandles: ['cmhandle'])
350 and: 'cm-handle deletion fails on batch'
351 mockInventoryPersistence.deleteDataNodes(_) >> { throw deleteListElementException }
352 and: 'cm-handle deletion fails on individual delete'
353 mockInventoryPersistence.deleteDataNode(_) >> { throw deleteListElementException }
354 when: 'registration is updated to delete cmhandle'
355 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
356 then: 'a failure response is received'
357 assert response.removedCmHandles.size() == 1
358 with(response.removedCmHandles[0]) {
359 assert it.status == Status.FAILURE
360 assert it.cmHandle == 'cmhandle'
361 assert it.registrationError == expectedError
362 assert it.errorText == expectedErrorText
364 and: 'the cm handle state is not updated to "DELETED"'
365 0 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_, CmHandleState.DELETED)
367 scenario | cmHandleId | deleteListElementException || expectedError | expectedErrorText
368 'cm-handle does not exist' | 'cmhandle' | new DataNodeNotFoundException('', '', '') || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
369 'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException('', '') || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
370 'an unexpected exception' | 'cmhandle' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
373 def getObjectUnderTest() {
374 return Spy(new NetworkCmProxyDataServiceImpl(spiedJsonObjectMapper, mockDmiDataOperations,
375 mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCmhandleQueries,
376 stubbedNetworkCmProxyCmHandlerQueryService, mockLcmEventsCmHandleStateHandler, mockCpsDataService,
377 mockModuleSyncStartedOnCmHandles))
380 def addPersistedYangModelCmHandles(ids) {
381 def yangModelCmHandles = ids.collect { new YangModelCmHandle(id:it) }
382 mockInventoryPersistence.getYangModelCmHandles(ids) >> yangModelCmHandles