Merge "Retry Module-Sync based on from last failure"
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImplSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Pantheon.tech
5  *  Modifications Copyright (C) 2021-2022 Bell Canada
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.ncmp.api.impl
24
25 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandlerQueryService
26 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
27 import org.onap.cps.ncmp.api.inventory.CmHandleState
28 import org.onap.cps.ncmp.api.inventory.CompositeState
29 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
30 import org.onap.cps.ncmp.api.inventory.LockReasonCategory
31 import org.onap.cps.ncmp.api.inventory.SyncState
32 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters
33 import org.onap.cps.ncmp.api.models.ConditionApiProperties
34 import org.onap.cps.ncmp.api.models.DmiPluginRegistration
35 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
36 import org.onap.cps.spi.exceptions.DataValidationException
37 import org.onap.cps.ncmp.api.inventory.sync.ModuleSyncService
38 import org.onap.cps.spi.model.CmHandleQueryServiceParameters
39 import org.onap.cps.spi.model.ConditionProperties
40 import spock.lang.Shared
41
42 import static org.onap.cps.ncmp.api.impl.operations.DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL
43 import static org.onap.cps.ncmp.api.impl.operations.DmiOperations.DataStoreEnum.PASSTHROUGH_RUNNING
44 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
45 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
46
47 import org.onap.cps.utils.JsonObjectMapper
48 import com.fasterxml.jackson.databind.ObjectMapper
49 import org.onap.cps.api.CpsAdminService
50 import org.onap.cps.api.CpsDataService
51 import org.onap.cps.api.CpsModuleService
52 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations
53 import org.onap.cps.spi.FetchDescendantsOption
54 import org.onap.cps.spi.model.DataNode
55 import org.springframework.http.HttpStatus
56 import org.springframework.http.ResponseEntity
57 import spock.lang.Specification
58
59 class NetworkCmProxyDataServiceImplSpec extends Specification {
60
61     def mockCpsDataService = Mock(CpsDataService)
62     def mockCpsModuleService = Mock(CpsModuleService)
63     def mockCpsAdminService = Mock(CpsAdminService)
64     def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
65     def mockDmiDataOperations = Mock(DmiDataOperations)
66     def nullNetworkCmProxyDataServicePropertyHandler = null
67     def mockInventoryPersistence = Mock(InventoryPersistence)
68     def mockModuleSyncService = Mock(ModuleSyncService)
69     def mockDmiPluginRegistration = Mock(DmiPluginRegistration)
70     def mockCpsCmHandlerQueryService = Mock(NetworkCmProxyCmHandlerQueryService)
71
72     def NO_TOPIC = null
73     def NO_REQUEST_ID = null
74     @Shared
75     def OPTIONS_PARAM = '(a=1,b=2)'
76     @Shared
77     def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
78
79     def objectUnderTest = new NetworkCmProxyDataServiceImpl(mockCpsDataService, spiedJsonObjectMapper, mockDmiDataOperations,
80         mockCpsModuleService, mockCpsAdminService, nullNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence,
81         mockModuleSyncService, mockCpsCmHandlerQueryService)
82
83     def cmHandleXPath = "/dmi-registry/cm-handles[@id='testCmHandle']"
84
85     def dataNode = new DataNode(leaves: ['id': 'some-cm-handle', 'dmi-service-name': 'testDmiService'])
86
87     def 'Write resource data for pass-through running from DMI using POST.'() {
88         given: 'cpsDataService returns valid datanode'
89             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
90                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
91         when: 'write resource data is called'
92             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
93                 'testResourceId', CREATE,
94                 '{some-json}', 'application/json')
95         then: 'DMI called with correct data'
96             1 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi('testCmHandle', 'testResourceId',
97                 CREATE, '{some-json}', 'application/json')
98                 >> { new ResponseEntity<>(HttpStatus.CREATED) }
99     }
100
101     def 'Write resource data for pass-through running from DMI using an invalid id.'() {
102         when: 'write resource data is called'
103             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('invalid cm handle name',
104                 'testResourceId', CREATE,
105                 '{some-json}', 'application/json')
106         then: 'exception is thrown'
107             thrown(DataValidationException.class)
108         and: 'DMI is not invoked'
109             0 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi(_, _, _, _, _)
110     }
111
112     def 'Get resource data for pass-through operational from DMI.'() {
113         given: 'get data node is called'
114             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
115                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
116         and: 'get resource data from DMI is called'
117             mockDmiDataOperations.getResourceDataFromDmi(
118                 'testCmHandle',
119                 'testResourceId',
120                 OPTIONS_PARAM,
121                 PASSTHROUGH_OPERATIONAL,
122                 NO_REQUEST_ID,
123                 NO_TOPIC) >> new ResponseEntity<>('dmi-response', HttpStatus.OK)
124         when: 'get resource data operational for cm-handle is called'
125             def response = objectUnderTest.getResourceDataOperationalForCmHandle('testCmHandle',
126                 'testResourceId',
127                 OPTIONS_PARAM,
128                 NO_TOPIC,
129                 NO_REQUEST_ID)
130         then: 'DMI returns a json response'
131             response == 'dmi-response'
132     }
133
134     def 'Get resource data for pass-through running from DMI.'() {
135         given: 'cpsDataService returns valid data node'
136             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
137                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
138         and: 'DMI returns valid response and data'
139             mockDmiDataOperations.getResourceDataFromDmi('testCmHandle',
140                 'testResourceId',
141                 OPTIONS_PARAM,
142                 PASSTHROUGH_RUNNING,
143                 NO_REQUEST_ID,
144                 NO_TOPIC) >> new ResponseEntity<>('{dmi-response}', HttpStatus.OK)
145         when: 'get resource data is called'
146             def response = objectUnderTest.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
147                 'testResourceId',
148                 OPTIONS_PARAM,
149                 NO_TOPIC,
150                 NO_REQUEST_ID)
151         then: 'get resource data returns expected response'
152             response == '{dmi-response}'
153     }
154
155     def 'Getting Yang Resources.'() {
156         when: 'yang resources is called'
157             objectUnderTest.getYangResourcesModuleReferences('some-cm-handle')
158         then: 'CPS module services is invoked for the correct dataspace and cm handle'
159             1 * mockCpsModuleService.getYangResourcesModuleReferences('NFP-Operational','some-cm-handle')
160     }
161
162     def 'Getting Yang Resources with an invalid #scenario.'() {
163         when: 'yang resources is called'
164             objectUnderTest.getYangResourcesModuleReferences('invalid cm handle with spaces')
165         then: 'a data validation exception is thrown'
166             thrown(DataValidationException)
167         and: 'CPS module services is not invoked'
168             0 * mockCpsModuleService.getYangResourcesModuleReferences(*_)
169     }
170
171     def 'Get a cm handle.'() {
172         given: 'the system returns a yang modelled cm handle'
173             def dmiServiceName = 'some service name'
174             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
175                 lockReason: CompositeState.LockReason.builder().lockReasonCategory(LockReasonCategory.LOCKED_MISBEHAVING).details("lock misbehaving details").build(),
176                 lastUpdateTime: 'some-timestamp',
177                 dataSyncEnabled: false,
178                 dataStores: dataStores())
179             def dmiProperties = [new YangModelCmHandle.Property('Book', 'Romance Novel')]
180             def publicProperties = [new YangModelCmHandle.Property('Public Book', 'Public Romance Novel')]
181             def yangModelCmHandle = new YangModelCmHandle(id: 'some-cm-handle', dmiServiceName: dmiServiceName,
182                 dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
183             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
184         when: 'getting cm handle details for a given cm handle id from ncmp service'
185             def result = objectUnderTest.getNcmpServiceCmHandle('some-cm-handle')
186         then: 'the result is a ncmpServiceCmHandle'
187             result.class == NcmpServiceCmHandle.class
188         and: 'the cm handle contains the cm handle id'
189             result.cmHandleId == 'some-cm-handle'
190         and: 'the cm handle contains the DMI Properties'
191             result.dmiProperties ==[ Book:'Romance Novel' ]
192         and: 'the cm handle contains the public Properties'
193             result.publicProperties == [ "Public Book":'Public Romance Novel' ]
194         and: 'the cm handle contains the cm handle composite state'
195             result.compositeState == compositeState
196
197     }
198
199     def 'Get a cm handle with an invalid id.'() {
200         when: 'getting cm handle details for a given cm handle id with an invalid name'
201             objectUnderTest.getNcmpServiceCmHandle('invalid cm handle with spaces')
202         then: 'an exception is thrown'
203             thrown(DataValidationException)
204         and: 'the yang model cm handle retriever is not invoked'
205             0 * mockInventoryPersistence.getYangModelCmHandle(*_)
206     }
207
208     def 'Get cm handle public properties'() {
209         given: 'a yang modelled cm handle'
210             def dmiProperties = [new YangModelCmHandle.Property('prop', 'some DMI property')]
211             def publicProperties = [new YangModelCmHandle.Property('public prop', 'some public prop')]
212             def yangModelCmHandle = new YangModelCmHandle(id:'some-cm-handle', dmiServiceName: 'some service name', dmiProperties: dmiProperties, publicProperties: publicProperties)
213         and: 'the system returns this yang modelled cm handle'
214             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
215         when: 'getting cm handle public properties for a given cm handle id from ncmp service'
216             def result = objectUnderTest.getCmHandlePublicProperties('some-cm-handle')
217         then: 'the result returns the correct data'
218             result == [ 'public prop' : 'some public prop' ]
219     }
220
221     def 'Get cm handle public properties with an invalid id.'() {
222         when: 'getting cm handle public properties for a given cm handle id with an invalid name'
223             objectUnderTest.getCmHandlePublicProperties('invalid cm handle with spaces')
224         then: 'an exception is thrown'
225             thrown(DataValidationException)
226         and: 'the yang model cm handle retriever is not invoked'
227             0 * mockInventoryPersistence.getYangModelCmHandle(*_)
228     }
229
230     def 'Get cm handle composite state'() {
231         given: 'a yang modelled cm handle'
232             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
233                 lockReason: CompositeState.LockReason.builder().lockReasonCategory(LockReasonCategory.LOCKED_MISBEHAVING).details("lock misbehaving details").build(),
234                 lastUpdateTime: 'some-timestamp',
235                 dataSyncEnabled: false,
236                 dataStores: dataStores())
237             def dmiProperties = [new YangModelCmHandle.Property('prop', 'some DMI property')]
238             def publicProperties = [new YangModelCmHandle.Property('public prop', 'some public prop')]
239             def yangModelCmHandle = new YangModelCmHandle(id:'some-cm-handle', dmiServiceName: 'some service name', dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
240         and: 'the system returns this yang modelled cm handle'
241             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
242         when: 'getting cm handle composite state for a given cm handle id from ncmp service'
243             def result = objectUnderTest.getCmHandleCompositeState('some-cm-handle')
244         then: 'the result returns the correct data'
245             result == compositeState
246     }
247
248     def 'Get cm handle composite state with an invalid id.'() {
249         when: 'getting cm handle composite state for a given cm handle id with an invalid name'
250             objectUnderTest.getCmHandleCompositeState('invalid cm handle with spaces')
251         then: 'an exception is thrown'
252             thrown(DataValidationException)
253         and: 'the yang model cm handle retriever is not invoked'
254             0 * mockInventoryPersistence.getYangModelCmHandle(_)
255     }
256
257     def 'Update resource data for pass-through running from dmi using POST #scenario DMI properties.'() {
258         given: 'cpsDataService returns valid datanode'
259             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
260                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
261         when: 'get resource data is called'
262             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
263                 'testResourceId', UPDATE,
264                 '{some-json}', 'application/json')
265         then: 'DMI called with correct data'
266             1 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi('testCmHandle', 'testResourceId',
267                 UPDATE, '{some-json}', 'application/json')
268                 >> { new ResponseEntity<>(HttpStatus.OK) }
269     }
270
271     def 'Verify modules and create anchor params'() {
272         given: 'dmi plugin registration return created cm handles'
273             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'service1', dmiModelPlugin: 'service1',
274                 dmiDataPlugin: 'service2')
275             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
276             mockDmiPluginRegistration.getCreatedCmHandles() >> [ncmpServiceCmHandle]
277         when: 'parse and create cm handle in dmi registration then sync module'
278             objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(mockDmiPluginRegistration)
279         then: 'validate params for creating anchor and list elements'
280         1 * mockCpsDataService.saveListElements('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, null) >> {
281             args -> {
282                 assert args[3].startsWith('{"cm-handles":[{"id":"some-cm-handle-id","state":{"cm-handle-state":"ADVISED","last-update-time":"20')
283             }
284         }
285     }
286
287     def 'Execute cm handle id search'() {
288         given: 'valid CmHandleQueryApiParameters input'
289             def cmHandleQueryApiParameters = new CmHandleQueryApiParameters()
290             def conditionApiProperties = new ConditionApiProperties()
291             conditionApiProperties.conditionName = 'hasAllModules'
292             conditionApiProperties.conditionParameters = [[moduleName: 'module-name-1']]
293             cmHandleQueryApiParameters.cmHandleQueryParameters = [conditionApiProperties]
294         and: 'valid CmHandleQueryParameters input'
295             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
296             def conditionProperties = new ConditionProperties()
297             conditionProperties.conditionName = 'hasAllModules'
298             conditionProperties.conditionParameters = [[moduleName: 'module-name-1']]
299             cmHandleQueryParameters.cmHandleQueryParameters = [conditionProperties]
300         and: 'query cm handle method return with a data node list'
301             mockCpsCmHandlerQueryService.queryCmHandles(cmHandleQueryParameters) >> [new DataNode(leaves: [id: 'cm-handle-id-1'])]
302         when: 'execute cm handle search is called'
303             def result = objectUnderTest.executeCmHandleIdSearch(cmHandleQueryApiParameters)
304         then: 'result is the same collection as returned by the CPS Data Service'
305             assert result == ['cm-handle-id-1'] as Set
306     }
307
308     def dataStores() {
309         CompositeState.DataStores.builder()
310             .operationalDataStore(CompositeState.Operational.builder()
311                 .syncState(SyncState.NONE_REQUESTED)
312                 .lastSyncTime('some-timestamp').build()).build()
313     }
314 }