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