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