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