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