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 org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
26 import org.onap.cps.api.CpsAdminService
27 import org.onap.cps.api.CpsDataService
28 import org.onap.cps.api.CpsModuleService
29 import org.onap.cps.ncmp.api.impl.exception.DmiRequestException
30 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations
31 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations
32 import org.onap.cps.ncmp.api.impl.operations.YangModelCmHandleRetriever
33 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse
34 import org.onap.cps.ncmp.api.models.DmiPluginRegistration
35 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
36 import org.onap.cps.ncmp.api.inventory.sync.ModuleSyncService
37 import org.onap.cps.spi.exceptions.AlreadyDefinedException
38 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
39 import org.onap.cps.spi.exceptions.DataValidationException
40 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
41 import org.onap.cps.utils.JsonObjectMapper
42 import spock.lang.Shared
43 import spock.lang.Specification
45 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
46 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_ALREADY_EXIST
47 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_INVALID_ID
48 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
49 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
50 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED
52 class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification {
55 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
58 def cmHandlesArray = ['cmHandle001']
60 def mockCpsDataService = Mock(CpsDataService)
61 def mockCpsModuleService = Mock(CpsModuleService)
62 def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
63 def mockCpsAdminService = Mock(CpsAdminService)
64 def mockDmiModelOperations = Mock(DmiModelOperations)
65 def mockDmiDataOperations = Mock(DmiDataOperations)
66 def mockNetworkCmProxyDataServicePropertyHandler = Mock(NetworkCmProxyDataServicePropertyHandler)
67 def mockYangModelCmHandleRetriever = Mock(YangModelCmHandleRetriever)
68 def mockModuleSyncService = Mock(ModuleSyncService)
70 def noTimestamp = null
71 def objectUnderTest = getObjectUnderTestWithModelSyncDisabled()
73 def 'DMI Registration: Create, Update & Delete operations are processed in the right order'() {
74 given: 'a registration with operations of all three types'
75 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
76 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
77 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
78 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
79 when: 'registration is processed'
80 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
81 // Spock validated invocation order between multiple then blocks
82 then: 'cm-handles are removed first'
83 1 * objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_)
84 then: 'cm-handles are created'
85 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_)
86 then: 'cm-handles are updated'
87 1 * mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_)
90 def 'DMI Registration: Response from all operations types are in response'() {
91 given: 'a registration with operations of all three types'
92 def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
93 dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
94 dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleId: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
95 dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
96 and: 'update cm-handles can be processed successfully'
97 def updateResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-2')]
98 mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_) >> updateResponses
99 and: 'create cm-handles can be processed successfully'
100 def createdResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-1')]
101 objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_) >> createdResponses
102 and: 'delete cm-handles can be processed successfully'
103 def removeResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-3')]
104 objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_) >> removeResponses
105 when: 'registration is processed'
106 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
107 then: 'response has values from all operations'
108 response.getRemovedCmHandles() == removeResponses
109 response.getCreatedCmHandles() == createdResponses
110 response.getUpdatedCmHandles() == updateResponses
115 def 'Create CM-handle Validation: Registration with valid Service names: #scenario'() {
116 given: 'a registration '
117 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
118 dmiDataPlugin: dmiDataPlugin)
119 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
120 when: 'update registration and sync module is called with correct DMI plugin information'
121 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
122 then: 'create cm handles registration and sync modules is called with the correct plugin information'
123 1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
125 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin
126 'combined DMI plugin' | 'service1' | '' | ''
127 'data & model DMI plugins' | '' | 'service1' | 'service2'
128 'data & model using same service' | '' | 'service1' | 'service1'
131 def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
132 given: 'a registration '
133 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
134 dmiDataPlugin: dmiDataPlugin)
135 dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
136 when: 'registration is called with incorrect DMI plugin information'
137 objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
138 then: 'a DMI Request Exception is thrown with correct message details'
139 def exceptionThrown = thrown(DmiRequestException.class)
140 assert exceptionThrown.getMessage().contains(expectedMessageDetails)
141 and: 'registration is not called'
142 0 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
144 scenario | dmiPlugin | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
145 'empty DMI plugins' | '' | '' | '' || 'No DMI plugin service names'
146 'blank DMI plugins' | ' ' | ' ' | ' ' || 'No DMI plugin service names'
147 'null DMI plugins' | null | null | null || 'No DMI plugin service names'
148 'all DMI plugins' | 'service1' | 'service2' | 'service3' || 'Cannot register combined plugin service name and other service names'
149 '(combined)DMI and Data Plugin' | 'service1' | '' | 'service2' || 'Cannot register combined plugin service name and other service names'
150 '(combined)DMI and model Plugin' | 'service1' | 'service2' | '' || 'Cannot register combined plugin service name and other service names'
151 'only model DMI plugin' | '' | 'service1' | '' || 'Cannot register just a Data or Model plugin service name'
152 'only data DMI plugin' | '' | '' | 'service1' || 'Cannot register just a Data or Model plugin service name'
155 def 'Create CM-Handle Successfully: #scenario.'() {
156 given: 'a registration without cm-handle properties'
157 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
158 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
159 when: 'registration is updated'
160 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
161 then: 'a successful response is received'
162 response.getCreatedCmHandles().size() == 1
163 with(response.getCreatedCmHandles().get(0)) {
164 assert it.status == Status.SUCCESS
165 assert it.cmHandle == 'cmhandle'
167 and: 'save list elements is invoked with the expected parameters'
169 def expectedJsonData = """{"cm-handles":[{"id":"cmhandle","dmi-service-name":"my-server","additional-properties":$expectedDmiProperties,"public-properties":$expectedPublicProperties}]}"""
170 1 * mockCpsDataService.saveListElements('NCMP-Admin', 'ncmp-dmi-registry',
171 '/dmi-registry', expectedJsonData, noTimestamp)
173 then: 'model sync is invoked with expected parameters'
174 1 * objectUnderTest.syncModulesAndCreateAnchor(_) >> { YangModelCmHandle yangModelCmHandle ->
176 assert yangModelCmHandle.id == 'cmhandle'
177 assert yangModelCmHandle.dmiServiceName == 'my-server'
178 assert spiedJsonObjectMapper.asJsonString(yangModelCmHandle.getPublicProperties()) == expectedPublicProperties
179 assert spiedJsonObjectMapper.asJsonString(yangModelCmHandle.getDmiProperties()) == expectedDmiProperties
184 scenario | dmiProperties | publicProperties || expectedDmiProperties | expectedPublicProperties
185 'with dmi & public properties' | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
186 'with only public properties' | [:] | ['public-key': 'public-value'] || '[]' | '[{"name":"public-key","value":"public-value"}]'
187 'with only dmi properties' | ['dmi-key': 'dmi-value'] | [:] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[]'
188 'without dmi & public properties' | [:] | [:] || '[]' | '[]'
192 def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed'() {
193 given: 'a registration with three cm-handles to be created'
194 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
195 createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
196 new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
197 new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
198 and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
199 mockCpsDataService.saveListElements(_, _, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
200 when: 'registration is updated to create cm-handles'
201 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
202 then: 'a response is received for all cm-handles'
203 response.getCreatedCmHandles().size() == 3
204 and: '1st and 3rd cm-handle are created successfully'
205 with(response.getCreatedCmHandles().get(0)) {
206 assert it.status == Status.SUCCESS
207 assert it.cmHandle == 'cmhandle1'
209 with(response.getCreatedCmHandles().get(2)) {
210 assert it.status == Status.SUCCESS
211 assert it.cmHandle == 'cmhandle3'
213 and: '2nd cm-handle creation fails'
214 with(response.getCreatedCmHandles().get(1)) {
215 assert it.status == Status.FAILURE
216 assert it.registrationError == UNKNOWN_ERROR
217 assert it.errorText == 'Failed'
218 assert it.cmHandle == 'cmhandle2'
222 def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
223 given: 'a registration without cm-handle properties'
224 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
225 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId)]
226 and: 'cm-handler registration fails: #scenario'
227 mockCpsDataService.saveListElements(_, _, _, _, _) >> { throw exception }
228 when: 'registration is updated'
229 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
230 then: 'a failure response is received'
231 response.getCreatedCmHandles().size() == 1
232 with(response.getCreatedCmHandles().get(0)) {
233 assert it.status == Status.FAILURE
234 assert it.cmHandle == cmHandleId
235 assert it.registrationError == expectedError
236 assert it.errorText == expectedErrorText
238 and: 'model-sync is not invoked'
239 0 * objectUnderTest.syncModulesAndCreateAnchor(_)
241 scenario | cmHandleId | exception || expectedError | expectedErrorText
242 'cm-handle already exist' | 'cmhandle' | new AlreadyDefinedException('', new RuntimeException()) || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
243 'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException("", "") || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
244 'unknown exception while registering cm-handle' | 'cmhandle' | new RuntimeException('Failed') || UNKNOWN_ERROR | 'Failed'
247 def 'Create CM-Handle Error Handling: Model Sync fails'() {
248 given: 'objects under test without disabled model sync'
249 def objectUnderTest = getObjectUnderTest()
250 and: 'a registration without cm-handle properties'
251 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
252 dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: 'cmhandle')]
253 and: 'cm-handler models sync fails'
254 objectUnderTest.syncModulesAndCreateAnchor(*_) >> { throw new RuntimeException('Model-Sync failed') }
255 when: 'registration is updated'
256 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
257 then: 'a failure response is received'
258 response.getCreatedCmHandles().size() == 1
259 with(response.getCreatedCmHandles().get(0)) {
260 assert it.status == Status.FAILURE
261 assert it.cmHandle == 'cmhandle'
262 assert it.registrationError == UNKNOWN_ERROR
263 assert it.errorText == 'Model-Sync failed'
265 and: 'cm-handle is registered'
266 1 * mockCpsDataService.saveListElements(*_)
269 def 'Update CM-Handle: Update Operation Response is added to the response'() {
270 given: 'a registration to update CmHandles'
271 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
272 updatedCmHandles: [{}])
273 and: 'cm-handle updates can be processed successfully'
274 def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
275 CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
276 CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLE_DOES_NOT_EXIST),
277 CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
278 mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
279 when: 'registration is updated'
280 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
281 then: 'the response contains updateOperationResponse'
282 assert response.getUpdatedCmHandles().size() == 4
283 assert response.getUpdatedCmHandles().containsAll(updateOperationResponse)
286 def 'Remove CmHandle Successfully: #scenario'() {
287 given: 'a registration'
288 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
289 removedCmHandles: ['cmhandle'])
291 mockCpsModuleService.deleteSchemaSet(_, 'cmhandle', CASCADE_DELETE_ALLOWED) >>
292 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
293 when: 'registration is updated to delete cmhandle'
294 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
295 then: 'delete list or list element is called'
296 1 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
297 and: 'successful response is received'
298 assert response.getRemovedCmHandles().size() == 1
299 with(response.getRemovedCmHandles().get(0)) {
300 assert it.status == Status.SUCCESS
301 assert it.cmHandle == 'cmhandle'
304 scenario | schemaSetExist
305 'schema-set exists and can be deleted successfully' | true
306 'schema-set does not exist' | false
309 def 'Remove CmHandle: All cm-handles delete requests are processed'() {
310 given: 'a registration with three cm-handles to be deleted'
311 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
312 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
313 and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
314 mockCpsDataService.deleteListOrListElement(_, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
315 when: 'registration is updated to delete cmhandles'
316 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
317 then: 'a response is received for all cm-handles'
318 response.getRemovedCmHandles().size() == 3
319 and: '1st and 3rd cm-handle deletes successfully'
320 with(response.getRemovedCmHandles().get(0)) {
321 assert it.status == Status.SUCCESS
322 assert it.cmHandle == 'cmhandle1'
324 with(response.getRemovedCmHandles().get(2)) {
325 assert it.status == Status.SUCCESS
326 assert it.cmHandle == 'cmhandle3'
328 and: '2nd cm-handle deletion fails'
329 with(response.getRemovedCmHandles().get(1)) {
330 assert it.status == Status.FAILURE
331 assert it.registrationError == UNKNOWN_ERROR
332 assert it.errorText == 'Failed'
333 assert it.cmHandle == 'cmhandle2'
337 def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
338 given: 'a registration'
339 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
340 removedCmHandles: ['cmhandle'])
341 and: 'schema set deletion failed with unknown error'
342 mockCpsModuleService.deleteSchemaSet(_, _, _) >> { throw new RuntimeException('Failed') }
343 when: 'registration is updated to delete cmhandle'
344 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
345 then: 'no exception is thrown'
347 and: 'cm-handle is not deleted'
348 0 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
349 and: 'a failure response is received'
350 assert response.getRemovedCmHandles().size() == 1
351 with(response.getRemovedCmHandles().get(0)) {
352 assert it.status == Status.FAILURE
353 assert it.cmHandle == 'cmhandle'
354 assert it.errorText == 'Failed'
355 assert it.registrationError == UNKNOWN_ERROR
359 def 'Remove CmHandle Error Handling: #scenario'() {
360 given: 'a registration'
361 def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
362 removedCmHandles: ['cmhandle'])
363 and: 'cm-handle deletion throws exception'
364 mockCpsDataService.deleteListOrListElement(_, _, _, _) >> { throw deleteListElementException }
365 when: 'registration is updated to delete cmhandle'
366 def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
367 then: 'no exception is thrown'
369 and: 'a failure response is received'
370 assert response.getRemovedCmHandles().size() == 1
371 with(response.getRemovedCmHandles().get(0)) {
372 assert it.status == Status.FAILURE
373 assert it.cmHandle == 'cmhandle'
374 assert it.registrationError == expectedError
375 assert it.errorText == expectedErrorText
378 scenario | cmHandleId | deleteListElementException || expectedError | expectedErrorText
379 'cm-handle does not exist' | 'cmhandle' | new DataNodeNotFoundException("", "", "") || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
380 'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException("", "") || CM_HANDLE_INVALID_ID | 'cm-handle has an invalid character(s) in id'
381 'an unexpected exception' | 'cmhandle' | new RuntimeException("Failed") || UNKNOWN_ERROR | 'Failed'
384 def getObjectUnderTestWithModelSyncDisabled() {
385 def objectUnderTest = getObjectUnderTest()
386 objectUnderTest.syncModulesAndCreateAnchor(*_) >> null
387 return objectUnderTest
390 def getObjectUnderTest() {
391 return Spy(new NetworkCmProxyDataServiceImpl(mockCpsDataService, spiedJsonObjectMapper, mockDmiDataOperations,
392 mockCpsModuleService, mockCpsAdminService, mockNetworkCmProxyDataServicePropertyHandler, mockYangModelCmHandleRetriever, mockModuleSyncService))