Registration Response for Create cmhandles operations
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImplRegistrationSpec.groovy
1 /*
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
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl
23
24 import 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.spi.exceptions.AlreadyDefinedException
37 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
38 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException
39 import org.onap.cps.utils.JsonObjectMapper
40 import spock.lang.Shared
41 import spock.lang.Specification
42
43 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_DOES_NOT_EXIST
44 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.CM_HANDLE_ALREADY_EXIST
45 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError.UNKNOWN_ERROR
46 import static org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.Status
47 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED
48
49 class NetworkCmProxyDataServiceImplRegistrationSpec extends Specification {
50
51     @Shared
52     def ncmpServiceCmHandle = new NcmpServiceCmHandle()
53
54     @Shared
55     def cmHandlesArray = ['cmHandle001']
56
57     def mockCpsDataService = Mock(CpsDataService)
58     def mockCpsModuleService = Mock(CpsModuleService)
59     def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
60     def mockCpsAdminService = Mock(CpsAdminService)
61     def mockDmiModelOperations = Mock(DmiModelOperations)
62     def mockDmiDataOperations = Mock(DmiDataOperations)
63     def mockNetworkCmProxyDataServicePropertyHandler = Mock(NetworkCmProxyDataServicePropertyHandler)
64     def mockYangModelCmHandleRetriever = Mock(YangModelCmHandleRetriever)
65
66     def noTimestamp = null
67     def objectUnderTest = getObjectUnderTestWithModelSyncDisabled()
68
69     def 'DMI Registration: Create, Update & Delete operations are processed in the right order'() {
70         given: 'a registration with operations of all three types'
71             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
72             dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleID: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
73             dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleID: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
74             dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
75         when: 'registration is processed'
76             objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
77             // Spock validated invocation order between multiple then blocks
78         then: 'cm-handles are removed first'
79             1 * objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_)
80         then: 'cm-handles are created'
81             1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_)
82         then: 'cm-handles are updated'
83             1 * mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_)
84     }
85
86     def 'DMI Registration: Response from all operations types are in response'() {
87         given: 'a registration with operations of all three types'
88             def dmiRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
89             dmiRegistration.setCreatedCmHandles([new NcmpServiceCmHandle(cmHandleID: 'cmhandle-1', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
90             dmiRegistration.setUpdatedCmHandles([new NcmpServiceCmHandle(cmHandleID: 'cmhandle-2', publicProperties: ['publicProp1': 'value'], dmiProperties: [:])])
91             dmiRegistration.setRemovedCmHandles(['cmhandle-2'])
92         and: 'update cm-handles can be processed successfully'
93             def updateResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-2')]
94             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(*_) >> updateResponses
95         and: 'create cm-handles can be processed successfully'
96             def createdResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-1')]
97             objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(*_) >> createdResponses
98         and: 'delete cm-handles can be processed successfully'
99             def removeResponses = [CmHandleRegistrationResponse.createSuccessResponse('cmhandle-3')]
100             objectUnderTest.parseAndRemoveCmHandlesInDmiRegistration(*_) >> removeResponses
101         when: 'registration is processed'
102             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiRegistration)
103         then: 'response has values from all operations'
104             response.getRemovedCmHandles() == removeResponses
105             response.getCreatedCmHandles() == createdResponses
106             response.getUpdatedCmHandles() == updateResponses
107
108
109     }
110
111     def 'Create CM-handle Validation: Registration with valid Service names: #scenario'() {
112         given: 'a registration '
113             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
114                 dmiDataPlugin: dmiDataPlugin)
115             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
116         when: 'update registration and sync module is called with correct DMI plugin information'
117             objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
118         then: 'create cm handles registration and sync modules is called with the correct plugin information'
119             1 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
120         where:
121             scenario                          | dmiPlugin  | dmiModelPlugin | dmiDataPlugin
122             'combined DMI plugin'             | 'service1' | ''             | ''
123             'data & model DMI plugins'        | ''         | 'service1'     | 'service2'
124             'data & model using same service' | ''         | 'service1'     | 'service1'
125     }
126
127     def 'Create CM-handle Validation: Invalid DMI plugin service name with #scenario'() {
128         given: 'a registration '
129             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: dmiPlugin, dmiModelPlugin: dmiModelPlugin,
130                 dmiDataPlugin: dmiDataPlugin)
131             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
132         when: 'registration is called with incorrect DMI plugin information'
133             objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
134         then: 'a DMI Request Exception is thrown with correct message details'
135             def exceptionThrown = thrown(DmiRequestException.class)
136             assert exceptionThrown.getMessage().contains(expectedMessageDetails)
137         and: 'registration is not called'
138             0 * objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration)
139         where:
140             scenario                         | dmiPlugin  | dmiModelPlugin | dmiDataPlugin || expectedMessageDetails
141             'empty DMI plugins'              | ''         | ''             | ''            || 'No DMI plugin service names'
142             'blank DMI plugins'              | ' '        | ' '            | ' '           || 'No DMI plugin service names'
143             'null DMI plugins'               | null       | null           | null          || 'No DMI plugin service names'
144             'all DMI plugins'                | 'service1' | 'service2'     | 'service3'    || 'Cannot register combined plugin service name and other service names'
145             '(combined)DMI and Data Plugin'  | 'service1' | ''             | 'service2'    || 'Cannot register combined plugin service name and other service names'
146             '(combined)DMI and model Plugin' | 'service1' | 'service2'     | ''            || 'Cannot register combined plugin service name and other service names'
147             'only model DMI plugin'          | ''         | 'service1'     | ''            || 'Cannot register just a Data or Model plugin service name'
148             'only data DMI plugin'           | ''         | ''             | 'service1'    || 'Cannot register just a Data or Model plugin service name'
149     }
150
151     def 'Create CM-Handle Successfully: #scenario.'() {
152         given: 'a registration without cm-handle properties'
153             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
154             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleID: 'cmhandle', dmiProperties: dmiProperties, publicProperties: publicProperties)]
155         when: 'registration is updated'
156             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
157         then: 'a successful response is received'
158             response.getCreatedCmHandles().size() == 1
159             with(response.getCreatedCmHandles().get(0)) {
160                 assert it.status == Status.SUCCESS
161                 assert it.cmHandle == 'cmhandle'
162             }
163         and: 'save list elements is invoked with the expected parameters'
164             interaction {
165                 def expectedJsonData = """{"cm-handles":[{"id":"cmhandle","dmi-service-name":"my-server","additional-properties":$expectedDmiProperties,"public-properties":$expectedPublicProperties}]}"""
166                 1 * mockCpsDataService.saveListElements('NCMP-Admin', 'ncmp-dmi-registry',
167                     '/dmi-registry', expectedJsonData, noTimestamp)
168             }
169         then: 'model sync is invoked with expected parameters'
170             1 * objectUnderTest.syncModulesAndCreateAnchor(_) >> { YangModelCmHandle yangModelCmHandle ->
171                 {
172                     assert yangModelCmHandle.id == 'cmhandle'
173                     assert yangModelCmHandle.dmiServiceName == 'my-server'
174                     assert spiedJsonObjectMapper.asJsonString(yangModelCmHandle.getPublicProperties()) == expectedPublicProperties
175                     assert spiedJsonObjectMapper.asJsonString(yangModelCmHandle.getDmiProperties()) == expectedDmiProperties
176
177                 }
178             }
179         where:
180             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
181             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
182             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || '[]'                                       | '[{"name":"public-key","value":"public-value"}]'
183             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | '[]'
184             'without dmi & public properties' | [:]                      | [:]                            || '[]'                                       | '[]'
185
186     }
187
188     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed'() {
189         given: 'a registration with three cm-handles to be created'
190             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
191                 createdCmHandles: [new NcmpServiceCmHandle(cmHandleID: 'cmhandle1'),
192                                    new NcmpServiceCmHandle(cmHandleID: 'cmhandle2'),
193                                    new NcmpServiceCmHandle(cmHandleID: 'cmhandle3')])
194         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
195             mockCpsDataService.saveListElements(_, _, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
196         when: 'registration is updated to create cm-handles'
197             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
198         then: 'a response is received for all cm-handles'
199             response.getCreatedCmHandles().size() == 3
200         and: '1st and 3rd cm-handle are created successfully'
201             with(response.getCreatedCmHandles().get(0)) {
202                 assert it.status == Status.SUCCESS
203                 assert it.cmHandle == 'cmhandle1'
204             }
205             with(response.getCreatedCmHandles().get(2)) {
206                 assert it.status == Status.SUCCESS
207                 assert it.cmHandle == 'cmhandle3'
208             }
209         and: '2nd cm-handle creation fails'
210             with(response.getCreatedCmHandles().get(1)) {
211                 assert it.status == Status.FAILURE
212                 assert it.registrationError == UNKNOWN_ERROR
213                 assert it.errorText == 'Failed'
214                 assert it.cmHandle == 'cmhandle2'
215             }
216     }
217
218     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
219         given: 'a registration without cm-handle properties'
220             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
221             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleID: 'cmhandle')]
222         and: 'cm-handler registration fails: #scenario'
223             mockCpsDataService.saveListElements(_, _, _, _, _) >> { throw exception }
224         when: 'registration is updated'
225             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
226         then: 'a failure response is received'
227             response.getCreatedCmHandles().size() == 1
228             with(response.getCreatedCmHandles().get(0)) {
229                 assert it.status == Status.FAILURE
230                 assert it.cmHandle == 'cmhandle'
231                 assert it.registrationError == expectedError
232                 assert it.errorText == expectedErrorText
233             }
234         and: 'model-sync is not invoked'
235             0 * objectUnderTest.syncModulesAndCreateAnchor(_)
236         where:
237             scenario                                        | exception                                               || expectedError           | expectedErrorText
238             'cm-handle already exist'                       | new AlreadyDefinedException('', new RuntimeException()) || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
239             'unknown exception while registering cm-handle' | new RuntimeException('Failed')                          || UNKNOWN_ERROR           | 'Failed'
240     }
241
242     def 'Create CM-Handle Error Handling: Model Sync fails'() {
243         given: 'objects under test without disabled model sync'
244             def objectUnderTest = getObjectUnderTest()
245         and: 'a registration without cm-handle properties'
246             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
247             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleID: 'cmhandle')]
248         and: 'cm-handler models sync fails'
249             objectUnderTest.syncModulesAndCreateAnchor(*_) >> { throw new RuntimeException('Model-Sync failed') }
250         when: 'registration is updated'
251             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
252         then: 'a failure response is received'
253             response.getCreatedCmHandles().size() == 1
254             with(response.getCreatedCmHandles().get(0)) {
255                 assert it.status == Status.FAILURE
256                 assert it.cmHandle == 'cmhandle'
257                 assert it.registrationError == UNKNOWN_ERROR
258                 assert it.errorText == 'Model-Sync failed'
259             }
260         and: 'cm-handle is registered'
261             1 * mockCpsDataService.saveListElements(*_)
262     }
263
264     def 'Update CM-Handle: Update Operation Response is added to the response'() {
265         given: 'a registration to update CmHandles'
266             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
267                 updatedCmHandles: [{}])
268         and: 'cm-handle updates can be processed successfully'
269             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
270                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
271                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLE_DOES_NOT_EXIST)]
272             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
273         when: 'registration is updated'
274             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
275         then: 'the response contains updateOperationResponse'
276             assert response.getUpdatedCmHandles().size() == 3
277             assert response.getUpdatedCmHandles().containsAll(updateOperationResponse)
278     }
279
280     def 'Remove CmHandle Successfully: #scenario'() {
281         given: 'a registration'
282             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
283                 removedCmHandles: ['cmhandle'])
284         and: '#scenario'
285             mockCpsModuleService.deleteSchemaSet(_, 'cmhandle', CASCADE_DELETE_ALLOWED) >>
286                 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
287         when: 'registration is updated to delete cmhandle'
288             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
289         then: 'delete list or list element is called'
290             1 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
291         and: 'successful response is received'
292             assert response.getRemovedCmHandles().size() == 1
293             with(response.getRemovedCmHandles().get(0)) {
294                 assert it.status == Status.SUCCESS
295                 assert it.cmHandle == 'cmhandle'
296             }
297         where:
298             scenario                                            | schemaSetExist
299             'schema-set exists and can be deleted successfully' | true
300             'schema-set does not exist'                         | false
301     }
302
303     def 'Remove CmHandle: All cm-handles delete requests are processed'() {
304         given: 'a registration with three cm-handles to be deleted'
305             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
306                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
307         and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
308             mockCpsDataService.deleteListOrListElement(_, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
309         when: 'registration is updated to delete cmhandles'
310             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
311         then: 'a response is received for all cm-handles'
312             response.getRemovedCmHandles().size() == 3
313         and: '1st and 3rd cm-handle deletes successfully'
314             with(response.getRemovedCmHandles().get(0)) {
315                 assert it.status == Status.SUCCESS
316                 assert it.cmHandle == 'cmhandle1'
317             }
318             with(response.getRemovedCmHandles().get(2)) {
319                 assert it.status == Status.SUCCESS
320                 assert it.cmHandle == 'cmhandle3'
321             }
322         and: '2nd cm-handle deletion fails'
323             with(response.getRemovedCmHandles().get(1)) {
324                 assert it.status == Status.FAILURE
325                 assert it.registrationError == UNKNOWN_ERROR
326                 assert it.errorText == 'Failed'
327                 assert it.cmHandle == 'cmhandle2'
328             }
329     }
330
331     def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
332         given: 'a registration'
333             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
334                 removedCmHandles: ['cmhandle'])
335         and: 'schema set deletion failed with unknown error'
336             mockCpsModuleService.deleteSchemaSet(_, _, _) >> { throw new RuntimeException('Failed') }
337         when: 'registration is updated to delete cmhandle'
338             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
339         then: 'no exception is thrown'
340             noExceptionThrown()
341         and: 'cm-handle is not deleted'
342             0 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
343         and: 'a failure response is received'
344             assert response.getRemovedCmHandles().size() == 1
345             with(response.getRemovedCmHandles().get(0)) {
346                 assert it.status == Status.FAILURE
347                 assert it.cmHandle == 'cmhandle'
348                 assert it.errorText == 'Failed'
349                 assert it.registrationError == UNKNOWN_ERROR
350             }
351     }
352
353     def 'Remove CmHandle Error Handling: #scenario'() {
354         given: 'a registration'
355             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
356                 removedCmHandles: ['cmhandle'])
357         and: 'cm-handle deletion throws exception'
358             mockCpsDataService.deleteListOrListElement(_, _, _, _) >> { throw deleteListElementException }
359         when: 'registration is updated to delete cmhandle'
360             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
361         then: 'no exception is thrown'
362             noExceptionThrown()
363         and: 'a failure response is received'
364             assert response.getRemovedCmHandles().size() == 1
365             with(response.getRemovedCmHandles().get(0)) {
366                 assert it.status == Status.FAILURE
367                 assert it.cmHandle == 'cmhandle'
368                 assert it.registrationError == expectedError
369                 assert it.errorText == expectedErrorText
370             }
371         where:
372             scenario                   | deleteListElementException                | expectedError            | expectedErrorText
373             'cm-handle does not exist' | new DataNodeNotFoundException("", "", "") | CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
374             'an unexpected exception'  | new RuntimeException("Failed")            | UNKNOWN_ERROR            | 'Failed'
375     }
376
377     def getObjectUnderTestWithModelSyncDisabled() {
378         def objectUnderTest = getObjectUnderTest()
379         objectUnderTest.syncModulesAndCreateAnchor(*_) >> null
380         return objectUnderTest
381     }
382
383     def getObjectUnderTest() {
384         return Spy(new NetworkCmProxyDataServiceImpl(mockCpsDataService, spiedJsonObjectMapper, mockDmiDataOperations, mockDmiModelOperations,
385             mockCpsModuleService, mockCpsAdminService, mockNetworkCmProxyDataServicePropertyHandler, mockYangModelCmHandleRetriever))
386     }
387 }