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