2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2022 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.inventory.CmHandleQueries
33 import org.onap.cps.ncmp.api.inventory.CmHandleState
34 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
35 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse
36 import org.onap.cps.ncmp.api.models.DmiPluginRegistration
37 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
38 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch
39 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
40 import org.onap.cps.spi.exceptions.DataValidationException
41 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
42 import org.onap.cps.utils.JsonObjectMapper
43 import spock.lang.Shared
44 import spock.lang.Specification
46 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
47 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_ALREADY_EXIST
48 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_INVALID_ID
49 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
50 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
51 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED
53 class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification {
56 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
58 def mockCpsModuleService = Mock(CpsModuleService)
59 def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
60 def mockDmiDataOperations = Mock(DmiDataOperations)
61 def mockNetworkCmProxyDataServicePropertyHandler = Mock(NetworkCmProxyDataServicePropertyHandler)
62 def mockInventoryPersistence = Mock(InventoryPersistence)
63 def mockCmhandleQueries = Mock(CmHandleQueries)
64 def stubbedNetworkCmProxyCmHandlerQueryService = Stub(NetworkCmProxyCmHandlerQueryService)
65 def mockLcmEventsCmHandleStateHandler = Mock(LcmEventsCmHandleStateHandler)
66 def mockCpsDataService = Mock(CpsDataService)
67 def mockModuleSyncStartedOnCmHandles = Mock(IMap<String, Object>)
68 def objectUnderTest = getObjectUnderTest()
70 def 'DMI Registration: Create, Update & Delete operations are processed in the right order'() {
71 given: 'a registration with operations of all three types'
72 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
73 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
74 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
75 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
76 when: 'registration is processed'
77 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
78 // Spock validated invocation order between multiple then blocks
79 then: 'cm-handles are removed first'
80 1 * objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_)
81 and: 'de-registered cm handle entry is removed from in progress map'
82 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle-2')
83 then: 'cm-handles are created'
84 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_)
85 then: 'cm-handles are updated'
86 1 * mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_)
89 def 'DMI Registration: Response from all operations types are in response'() {
90 given: 'a registration with operations of all three types'
91 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
92 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
93 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
94 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
95 and: 'update cm-handles can be processed successfully'
96 def updateResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-2')]
97 mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_) >> updateResponses
98 and: 'create cm-handles can be processed successfully'
99 def createdResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-1')]
100 objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_) >> createdResponses
101 and: 'delete cm-handles can be processed successfully'
102 def removeResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-3')]
103 objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_) >> removeResponses
104 when: 'registration is processed'
105 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
106 then: 'response has values from all operations'
107 response.getRemovedCmHandles() == removeResponses
108 response.getCreatedCmHandles() == createdResponses
109 response.getUpdatedCmHandles() == updateResponses
112 def 'Create CM-handle Validation: Registration with valid Service names: #scenario'() {
113 given: 'a registration '
114 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
115 dmiDataPlugin: dmiDataPlugin)
116 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
117 when: 'update registration and sync module is called with correct DMI plugin information'
118 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
119 then: 'create cm handles registration and sync modules is called with the correct plugin information'
120 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
122 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin
123 'combined DMI plugin' | 'service1' | '' | ''
124 'data & model DMI plugins' | '' | 'service1' | 'service2'
125 'data & model using same service' | '' | 'service1' | 'service1'
128 def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
129 given: 'a registration '
130 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
131 dmiDataPlugin: dmiDataPlugin)
132 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
133 when: 'registration is called with incorrect DMI plugin information'
134 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
135 then: 'a DMI Request Exception is thrown with correct message details'
136 def exceptionThrown = thrown(DmiRequestException.class)
137 assert exceptionThrown.getMessage().contains(expectedMessageDetails)
138 and: 'registration is not called'
139 0 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
141 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
142 'empty DMI plugins' | '' | '' | '' || 'No DMI plugin service names'
143 'blank DMI plugins' | ' ' | ' ' | ' ' || 'No DMI plugin service names'
144 'null DMI plugins' | null | null | null || 'No DMI plugin service names'
145 'all DMI plugins' | 'service1' | 'service2' | 'service3' || 'Cannot register combined plugin service name and other service names'
146 '(combined)DMI and Data Plugin' | 'service1' | '' | 'service2' || 'Cannot register combined plugin service name and other service names'
147 '(combined)DMI and model Plugin' | 'service1' | 'service2' | '' || 'Cannot register combined plugin service name and other service names'
148 'only model DMI plugin' | '' | 'service1' | '' || 'Cannot register just a Data or Model plugin service name'
149 'only data DMI plugin' | '' | '' | 'service1' || 'Cannot register just a Data or Model plugin service name'
152 def 'Create CM-Handle Successfully: #scenario.'() {
153 given: 'a registration without cm-handle properties'
154 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
155 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
156 when: 'registration is updated'
157 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
158 then: 'a successful response is received'
159 response.getCreatedCmHandles().size() == 1
160 with(response.getCreatedCmHandles().get(0)) {
161 assert it.status == Status.SUCCESS
162 assert it.cmHandle == 'cmhandle'
164 and: 'state handler is invoked with the expected parameters'
165 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(_) >> {
168 def cmHandleStatePerCmHandle = (args[0] as Map)
169 cmHandleStatePerCmHandle.each {
170 assert (it.key.id == 'cmhandle'
171 && it.key.dmiServiceName == 'my-server'
172 && it.value == CmHandleState.ADVISED)
177 scenario | dmiProperties | publicProperties || expectedDmiProperties | expectedPublicProperties
178 'with dmi & public properties' | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
179 'with only public properties' | [:] | ['public-key': 'public-value'] || '[]' | '[{"name":"public-key","value":"public-value"}]'
180 'with only dmi properties' | ['dmi-key': 'dmi-value'] | [:] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[]'
181 'without dmi & public properties' | [:] | [:] || '[]' | '[]'
184 def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed with some failures'() {
185 given: 'a registration with three cm-handles to be created'
186 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
187 createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
188 new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
189 new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
190 and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
191 def xpath = "somePathWithId[@id='cmhandle2']"
192 mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(*_) >> { throw new AlreadyDefinedExceptionBatch([xpath]) }
193 when: 'registration is updated to create cm-handles'
194 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
195 then: 'a response is received for all cm-handles'
196 response.getCreatedCmHandles().size() == 1
197 and: 'all cm-handles creation fails'
198 response.getCreatedCmHandles().each {
199 assert it.cmHandle == 'cmhandle2'
200 assert it.status == Status.FAILURE
201 assert it.registrationError == CM_HANDLE_ALREADY_EXIST
202 assert it.errorText == 'cm-handle already exists'
206 def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
207 given: 'a registration without cm-handle properties'
208 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
209 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId)]
210 and: 'cm-handler registration fails: #scenario'
211 mockLcmEventsCmHandleStateHandler.updateCmHandleStateBatch(*_) >> { throw exception }
212 when: 'registration is updated'
213 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
214 then: 'a failure response is received'
215 response.getCreatedCmHandles().size() == 1
216 with(response.getCreatedCmHandles().get(0)) {
217 assert it.status == Status.FAILURE
218 assert it.cmHandle == cmHandleId
219 assert it.registrationError == expectedError
220 assert it.errorText == expectedErrorText
223 scenario | cmHandleId | exception || expectedError | expectedErrorText
224 'cm-handle already exist' | 'cmhandle' | new AlreadyDefinedExceptionBatch(["path[@id='${cmHandleId}']".toString()]) || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
225 'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException("", "") || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
226 'unknown exception while registering cm-handle' | 'cmhandle' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
229 def 'Update CM-Handle: Update Operation Response is added to the response'() {
230 given: 'a registration to update CmHandles'
231 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
232 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.getUpdatedCmHandles().size() == 4
243 assert response.getUpdatedCmHandles().containsAll(updateOperationResponse)
246 def 'Remove CmHandle Successfully: #scenario'() {
247 given: 'a registration'
248 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
249 removedCmHandles: ['cmhandle'])
251 mockCpsModuleService.deleteSchemaSet(_, 'cmhandle', CASCADE_DELETE_ALLOWED) >>
252 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
253 when: 'registration is updated to delete cmhandle'
254 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
255 then: 'the cmHandle state is updated to "DELETING"'
256 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleState(_, CmHandleState.DELETING)
257 and: 'method to delete relevant schema set is called once'
258 1 * mockInventoryPersistence.deleteSchemaSetWithCascade(_)
259 and: 'method to delete relevant list/list element is called once'
260 1 * mockInventoryPersistence.deleteListOrListElement(_)
261 and: 'successful response is received'
262 assert response.getRemovedCmHandles().size() == 1
263 with(response.getRemovedCmHandles().get(0)) {
264 assert it.status == Status.SUCCESS
265 assert it.cmHandle == 'cmhandle'
267 and: 'the cmHandle state is updated to "DELETED"'
268 1 * mockLcmEventsCmHandleStateHandler.updateCmHandleState(_, CmHandleState.DELETED)
270 scenario | schemaSetExist
271 'schema-set exists and can be deleted successfully' | true
272 'schema-set does not exist' | false
275 def 'Remove CmHandle: Partial Success'() {
276 given: 'a registration with three cm-handles to be deleted'
277 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
278 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
279 and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
280 mockInventoryPersistence.deleteListOrListElement(_) >> {} >> { throw new RuntimeException("Failed") } >> {}
281 when: 'registration is updated to delete cmhandles'
282 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
283 then: 'a response is received for all cm-handles'
284 response.getRemovedCmHandles().size() == 3
285 and: 'successfully de-registered cm handle entries are removed from in progress map'
286 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle1')
287 1 * mockModuleSyncStartedOnCmHandles.remove('cmhandle3')
288 and: 'failed de-registered cm handle entries should not be removed from in progress map'
289 0 * mockModuleSyncStartedOnCmHandles.remove('cmhandle2')
290 and: '1st and 3rd cm-handle deletes successfully'
291 with(response.getRemovedCmHandles().get(0)) {
292 assert it.status == Status.SUCCESS
293 assert it.cmHandle == 'cmhandle1'
295 with(response.getRemovedCmHandles().get(2)) {
296 assert it.status == Status.SUCCESS
297 assert it.cmHandle == 'cmhandle3'
299 and: '2nd cm-handle deletion fails'
300 with(response.getRemovedCmHandles().get(1)) {
301 assert it.status == Status.FAILURE
302 assert it.registrationError == UNKNOWN_ERROR
303 assert it.errorText == 'Failed'
304 assert it.cmHandle == 'cmhandle2'
308 def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
309 given: 'a registration'
310 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
311 removedCmHandles: ['cmhandle'])
312 and: 'schema set deletion failed with unknown error'
313 mockInventoryPersistence.deleteSchemaSetWithCascade(_) >> { throw new RuntimeException('Failed') }
314 when: 'registration is updated to delete cmhandle'
315 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
316 then: 'no exception is thrown'
318 and: 'cm-handle is not deleted'
319 0 * mockInventoryPersistence.deleteListOrListElement(_)
320 and: 'the cmHandle state is not updated to "DELETED"'
321 0 * mockLcmEventsCmHandleStateHandler.updateCmHandleState(_, CmHandleState.DELETED)
322 and: 'a failure response is received'
323 assert response.getRemovedCmHandles().size() == 1
324 with(response.getRemovedCmHandles().get(0)) {
325 assert it.status == Status.FAILURE
326 assert it.cmHandle == 'cmhandle'
327 assert it.errorText == 'Failed'
328 assert it.registrationError == UNKNOWN_ERROR
332 def 'Remove CmHandle Error Handling: #scenario'() {
333 given: 'a registration'
334 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
335 removedCmHandles: ['cmhandle'])
336 and: 'cm-handle deletion throws exception'
337 mockInventoryPersistence.deleteListOrListElement(_) >> { throw deleteListElementException }
338 when: 'registration is updated to delete cmhandle'
339 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
340 then: 'a failure response is received'
341 assert response.getRemovedCmHandles().size() == 1
342 with(response.getRemovedCmHandles().get(0)) {
343 assert it.status == Status.FAILURE
344 assert it.cmHandle == 'cmhandle'
345 assert it.registrationError == expectedError
346 assert it.errorText == expectedErrorText
348 and: 'the cm handle state is not updated to "DELETED"'
349 0 * mockLcmEventsCmHandleStateHandler.updateCmHandleState(_, CmHandleState.DELETED)
351 scenario | cmHandleId | deleteListElementException || expectedError | expectedErrorText
352 'cm-handle does not exist' | 'cmhandle' | new DataNodeNotFoundException("", "", "") || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
353 'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException("", "") || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
354 'an unexpected exception' | 'cmhandle' | new RuntimeException("Failed") || UNKNOWN_ERROR | 'Failed'
357 def getObjectUnderTest() {
358 return Spy(new NetworkCmProxyDataServiceImpl(spiedJsonObjectMapper, mockDmiDataOperations,
359 mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCmhandleQueries,
360 stubbedNetworkCmProxyCmHandlerQueryService, mockLcmEventsCmHandleStateHandler, mockCpsDataService,
361 mockModuleSyncStartedOnCmHandles))