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