Unable to change state from LOCKED to ADVISED
[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                 1 * mockCpsDataService.saveListElements('NCMP-Admin', 'ncmp-dmi-registry',
168                     '/dmi-registry', _, noTimestamp) >> {
169                     args -> {
170                         assert args[3].startsWith('{"cm-handles":[{"id":"cmhandle","dmi-service-name":"my-server","state":{"cm-handle-state":"ADVISED","last-update-time":"20')
171                         assert args[3].contains(expectedDmiProperties)
172                         assert args[3].contains(expectedPublicProperties)
173                     }
174                 }
175             }
176         where:
177             scenario                          | dmiProperties            | publicProperties               || expectedDmiProperties                      | expectedPublicProperties
178             'with dmi & public properties'    | ['dmi-key': 'dmi-value'] | ['public-key': 'public-value'] || '[{"name":"dmi-key","value":"dmi-value"}]' | '[{"name":"public-key","value":"public-value"}]'
179             'with only public properties'     | [:]                      | ['public-key': 'public-value'] || '[]'                                       | '[{"name":"public-key","value":"public-value"}]'
180             'with only dmi properties'        | ['dmi-key': 'dmi-value'] | [:]                            || '[{"name":"dmi-key","value":"dmi-value"}]' | '[]'
181             'without dmi & public properties' | [:]                      | [:]                            || '[]'                                       | '[]'
182
183     }
184
185     def 'Create CM-Handle Multiple Requests: All cm-handles creation requests are processed'() {
186         given: 'a registration with three cm-handles to be created'
187             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
188                 createdCmHandles: [new NcmpServiceCmHandle(cmHandleId: 'cmhandle1'),
189                                    new NcmpServiceCmHandle(cmHandleId: 'cmhandle2'),
190                                    new NcmpServiceCmHandle(cmHandleId: 'cmhandle3')])
191         and: 'cm-handle creation is successful for 1st and 3rd; failed for 2nd'
192             mockCpsDataService.saveListElements(_, _, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
193         when: 'registration is updated to create cm-handles'
194             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
195         then: 'a response is received for all cm-handles'
196             response.getCreatedCmHandles().size() == 3
197         and: '1st and 3rd cm-handle are created successfully'
198             with(response.getCreatedCmHandles().get(0)) {
199                 assert it.status == Status.SUCCESS
200                 assert it.cmHandle == 'cmhandle1'
201             }
202             with(response.getCreatedCmHandles().get(2)) {
203                 assert it.status == Status.SUCCESS
204                 assert it.cmHandle == 'cmhandle3'
205             }
206         and: '2nd cm-handle creation fails'
207             with(response.getCreatedCmHandles().get(1)) {
208                 assert it.status == Status.FAILURE
209                 assert it.registrationError == UNKNOWN_ERROR
210                 assert it.errorText == 'Failed'
211                 assert it.cmHandle == 'cmhandle2'
212             }
213     }
214
215     def 'Create CM-Handle Error Handling: Registration fails: #scenario'() {
216         given: 'a registration without cm-handle properties'
217             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server')
218             dmiPluginRegistration.createdCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId)]
219         and: 'cm-handler registration fails: #scenario'
220             mockCpsDataService.saveListElements(_, _, _, _, _) >> { throw exception }
221         when: 'registration is updated'
222             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
223         then: 'a failure response is received'
224             response.getCreatedCmHandles().size() == 1
225             with(response.getCreatedCmHandles().get(0)) {
226                 assert it.status == Status.FAILURE
227                 assert it.cmHandle ==  cmHandleId
228                 assert it.registrationError == expectedError
229                 assert it.errorText == expectedErrorText
230             }
231         where:
232             scenario                                        | cmHandleId             | exception                                               || expectedError           | expectedErrorText
233             'cm-handle already exist'                       | 'cmhandle'             | new AlreadyDefinedException('', new RuntimeException()) || CM_HANDLE_ALREADY_EXIST | 'cm-handle already exists'
234             'cm-handle has invalid name'                    | 'cm handle with space' | new DataValidationException("", "")                     || CM_HANDLE_INVALID_ID    | 'cm-handle has an invalid character(s) in id'
235             'unknown exception while registering cm-handle' | 'cmhandle'             | new RuntimeException('Failed')                          || UNKNOWN_ERROR           | 'Failed'
236     }
237
238     def 'Update CM-Handle: Update Operation Response is added to the response'() {
239         given: 'a registration to update CmHandles'
240             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
241                 updatedCmHandles: [{}])
242         and: 'cm-handle updates can be processed successfully'
243             def updateOperationResponse = [CmHandleRegistrationResponse.createSuccessResponse('cm-handle-1'),
244                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-2', new Exception("Failed")),
245                                            CmHandleRegistrationResponse.createFailureResponse('cm-handle-3', CM_HANDLE_DOES_NOT_EXIST),
246                                            CmHandleRegistrationResponse.createFailureResponse('cm handle 4', CM_HANDLE_INVALID_ID)]
247             mockNetworkCmProxyDataServicePropertyHandler.updateCmHandleProperties(_) >> updateOperationResponse
248         when: 'registration is updated'
249             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
250         then: 'the response contains updateOperationResponse'
251             assert response.getUpdatedCmHandles().size() == 4
252             assert response.getUpdatedCmHandles().containsAll(updateOperationResponse)
253     }
254
255     def 'Remove CmHandle Successfully: #scenario'() {
256         given: 'a registration'
257             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
258                 removedCmHandles: ['cmhandle'])
259         and: '#scenario'
260             mockCpsModuleService.deleteSchemaSet(_, 'cmhandle', CASCADE_DELETE_ALLOWED) >>
261                 { if (!schemaSetExist) { throw new SchemaSetNotFoundException("", "") } }
262         when: 'registration is updated to delete cmhandle'
263             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
264         then: 'delete list or list element is called'
265             1 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
266         and: 'successful response is received'
267             assert response.getRemovedCmHandles().size() == 1
268             with(response.getRemovedCmHandles().get(0)) {
269                 assert it.status == Status.SUCCESS
270                 assert it.cmHandle == 'cmhandle'
271             }
272         where:
273             scenario                                            | schemaSetExist
274             'schema-set exists and can be deleted successfully' | true
275             'schema-set does not exist'                         | false
276     }
277
278     def 'Remove CmHandle: All cm-handles delete requests are processed'() {
279         given: 'a registration with three cm-handles to be deleted'
280             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
281                 removedCmHandles: ['cmhandle1', 'cmhandle2', 'cmhandle3'])
282         and: 'cm-handle deletion is successful for 1st and 3rd; failed for 2nd'
283             mockCpsDataService.deleteListOrListElement(_, _, _, _) >> {} >> { throw new RuntimeException("Failed") } >> {}
284         when: 'registration is updated to delete cmhandles'
285             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
286         then: 'a response is received for all cm-handles'
287             response.getRemovedCmHandles().size() == 3
288         and: '1st and 3rd cm-handle deletes successfully'
289             with(response.getRemovedCmHandles().get(0)) {
290                 assert it.status == Status.SUCCESS
291                 assert it.cmHandle == 'cmhandle1'
292             }
293             with(response.getRemovedCmHandles().get(2)) {
294                 assert it.status == Status.SUCCESS
295                 assert it.cmHandle == 'cmhandle3'
296             }
297         and: '2nd cm-handle deletion fails'
298             with(response.getRemovedCmHandles().get(1)) {
299                 assert it.status == Status.FAILURE
300                 assert it.registrationError == UNKNOWN_ERROR
301                 assert it.errorText == 'Failed'
302                 assert it.cmHandle == 'cmhandle2'
303             }
304     }
305
306     def 'Remove CmHandle Error Handling: Schema Set Deletion failed'() {
307         given: 'a registration'
308             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
309                 removedCmHandles: ['cmhandle'])
310         and: 'schema set deletion failed with unknown error'
311             mockCpsModuleService.deleteSchemaSet(_, _, _) >> { throw new RuntimeException('Failed') }
312         when: 'registration is updated to delete cmhandle'
313             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
314         then: 'no exception is thrown'
315             noExceptionThrown()
316         and: 'cm-handle is not deleted'
317             0 * mockCpsDataService.deleteListOrListElement(_, _, _, _)
318         and: 'a failure response is received'
319             assert response.getRemovedCmHandles().size() == 1
320             with(response.getRemovedCmHandles().get(0)) {
321                 assert it.status == Status.FAILURE
322                 assert it.cmHandle == 'cmhandle'
323                 assert it.errorText == 'Failed'
324                 assert it.registrationError == UNKNOWN_ERROR
325             }
326     }
327
328     def 'Remove CmHandle Error Handling: #scenario'() {
329         given: 'a registration'
330             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'my-server',
331                 removedCmHandles: ['cmhandle'])
332         and: 'cm-handle deletion throws exception'
333             mockCpsDataService.deleteListOrListElement(_, _, _, _) >> { throw deleteListElementException }
334         when: 'registration is updated to delete cmhandle'
335             def response = objectUnderTest.updateDmiRegistrationAndSyncModule(dmiPluginRegistration)
336         then: 'no exception is thrown'
337             noExceptionThrown()
338         and: 'a failure response is received'
339             assert response.getRemovedCmHandles().size() == 1
340             with(response.getRemovedCmHandles().get(0)) {
341                 assert it.status == Status.FAILURE
342                 assert it.cmHandle == 'cmhandle'
343                 assert it.registrationError == expectedError
344                 assert it.errorText == expectedErrorText
345             }
346         where:
347             scenario                     | cmHandleId             | deleteListElementException                ||  expectedError           | expectedErrorText
348             'cm-handle does not exist'   | 'cmhandle'             | new DataNodeNotFoundException("", "", "") || CM_HANDLE_DOES_NOT_EXIST | 'cm-handle does not exist'
349             'cm-handle has invalid name' | 'cm handle with space' | new DataValidationException("", "")       || CM_HANDLE_INVALID_ID     | 'cm-handle has an invalid character(s) in id'
350             'an unexpected exception'    | 'cmhandle'             | new RuntimeException("Failed")            || UNKNOWN_ERROR            | 'Failed'
351     }
352
353     def getObjectUnderTest() {
354         return Spy(new NetworkCmProxyDataServiceImpl(mockCpsDataService, spiedJsonObjectMapper, mockDmiDataOperations,
355             mockCpsModuleService, mockCpsAdminService, mockNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence,
356             mockModuleSyncService, stubbedNetworkCmProxyCmHandlerQueryService))
357     }
358 }