Move persistence related methods
[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.DataStoreSyncState
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.spi.model.CmHandleQueryServiceParameters
38 import spock.lang.Shared
39
40 import java.util.stream.Collectors
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.CpsDataService
50 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations
51 import org.onap.cps.spi.FetchDescendantsOption
52 import org.onap.cps.spi.model.DataNode
53 import org.springframework.http.HttpStatus
54 import org.springframework.http.ResponseEntity
55 import spock.lang.Specification
56
57 class NetworkCmProxyDataServiceImplSpec extends Specification {
58
59     def mockCpsDataService = Mock(CpsDataService)
60     def spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
61     def mockDmiDataOperations = Mock(DmiDataOperations)
62     def nullNetworkCmProxyDataServicePropertyHandler = null
63     def mockInventoryPersistence = Mock(InventoryPersistence)
64     def mockDmiPluginRegistration = Mock(DmiPluginRegistration)
65     def mockCpsCmHandlerQueryService = Mock(NetworkCmProxyCmHandlerQueryService)
66
67     def NO_TOPIC = null
68     def NO_REQUEST_ID = null
69     @Shared
70     def OPTIONS_PARAM = '(a=1,b=2)'
71     @Shared
72     def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle-id')
73
74     def objectUnderTest = new NetworkCmProxyDataServiceImpl(spiedJsonObjectMapper, mockDmiDataOperations,
75         nullNetworkCmProxyDataServicePropertyHandler, mockInventoryPersistence, mockCpsCmHandlerQueryService)
76
77     def cmHandleXPath = "/dmi-registry/cm-handles[@id='testCmHandle']"
78
79     def dataNode = new DataNode(leaves: ['id': 'some-cm-handle', 'dmi-service-name': 'testDmiService'])
80
81     def 'Write resource data for pass-through running from DMI using POST.'() {
82         given: 'cpsDataService returns valid datanode'
83             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
84                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
85         when: 'write resource data is called'
86             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
87                 'testResourceId', CREATE,
88                 '{some-json}', 'application/json')
89         then: 'DMI called with correct data'
90             1 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi('testCmHandle', 'testResourceId',
91                 CREATE, '{some-json}', 'application/json')
92                 >> { new ResponseEntity<>(HttpStatus.CREATED) }
93     }
94
95     def 'Write resource data for pass-through running from DMI using an invalid id.'() {
96         when: 'write resource data is called'
97             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('invalid cm handle name',
98                 'testResourceId', CREATE,
99                 '{some-json}', 'application/json')
100         then: 'exception is thrown'
101             thrown(DataValidationException.class)
102         and: 'DMI is not invoked'
103             0 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi(_, _, _, _, _)
104     }
105
106     def 'Get resource data for pass-through operational from DMI.'() {
107         given: 'get data node is called'
108             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
109                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
110         and: 'get resource data from DMI is called'
111             mockDmiDataOperations.getResourceDataFromDmi(
112                 'testCmHandle',
113                 'testResourceId',
114                 OPTIONS_PARAM,
115                 PASSTHROUGH_OPERATIONAL,
116                 NO_REQUEST_ID,
117                 NO_TOPIC) >> new ResponseEntity<>('dmi-response', HttpStatus.OK)
118         when: 'get resource data operational for cm-handle is called'
119             def response = objectUnderTest.getResourceDataOperationalForCmHandle('testCmHandle',
120                 'testResourceId',
121                 OPTIONS_PARAM,
122                 NO_TOPIC,
123                 NO_REQUEST_ID)
124         then: 'DMI returns a json response'
125             response == 'dmi-response'
126     }
127
128     def 'Get resource data for pass-through running from DMI.'() {
129         given: 'cpsDataService returns valid data node'
130             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
131                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
132         and: 'DMI returns valid response and data'
133             mockDmiDataOperations.getResourceDataFromDmi('testCmHandle',
134                 'testResourceId',
135                 OPTIONS_PARAM,
136                 PASSTHROUGH_RUNNING,
137                 NO_REQUEST_ID,
138                 NO_TOPIC) >> new ResponseEntity<>('{dmi-response}', HttpStatus.OK)
139         when: 'get resource data is called'
140             def response = objectUnderTest.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
141                 'testResourceId',
142                 OPTIONS_PARAM,
143                 NO_TOPIC,
144                 NO_REQUEST_ID)
145         then: 'get resource data returns expected response'
146             response == '{dmi-response}'
147     }
148
149     def 'Getting Yang Resources.'() {
150         when: 'yang resources is called'
151             objectUnderTest.getYangResourcesModuleReferences('some-cm-handle')
152         then: 'CPS module services is invoked for the correct dataspace and cm handle'
153             1 * mockInventoryPersistence.getYangResourcesModuleReferences('some-cm-handle')
154     }
155
156     def 'Getting Yang Resources with an invalid #scenario.'() {
157         when: 'yang resources is called'
158             objectUnderTest.getYangResourcesModuleReferences('invalid cm handle with spaces')
159         then: 'a data validation exception is thrown'
160             thrown(DataValidationException)
161         and: 'CPS module services is not invoked'
162             0 * mockInventoryPersistence.getYangResourcesModuleReferences(*_)
163     }
164
165     def 'Get a cm handle.'() {
166         given: 'the system returns a yang modelled cm handle'
167             def dmiServiceName = 'some service name'
168             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
169                 lockReason: CompositeState.LockReason.builder().lockReasonCategory(LockReasonCategory.LOCKED_MODULE_SYNC_FAILED).details("lock details").build(),
170                 lastUpdateTime: 'some-timestamp',
171                 dataSyncEnabled: false,
172                 dataStores: dataStores())
173             def dmiProperties = [new YangModelCmHandle.Property('Book', 'Romance Novel')]
174             def publicProperties = [new YangModelCmHandle.Property('Public Book', 'Public Romance Novel')]
175             def yangModelCmHandle = new YangModelCmHandle(id: 'some-cm-handle', dmiServiceName: dmiServiceName,
176                 dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
177             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
178         when: 'getting cm handle details for a given cm handle id from ncmp service'
179             def result = objectUnderTest.getNcmpServiceCmHandle('some-cm-handle')
180         then: 'the result is a ncmpServiceCmHandle'
181             result.class == NcmpServiceCmHandle.class
182         and: 'the cm handle contains the cm handle id'
183             result.cmHandleId == 'some-cm-handle'
184         and: 'the cm handle contains the DMI Properties'
185             result.dmiProperties ==[ Book:'Romance Novel' ]
186         and: 'the cm handle contains the public Properties'
187             result.publicProperties == [ "Public Book":'Public Romance Novel' ]
188         and: 'the cm handle contains the cm handle composite state'
189             result.compositeState == compositeState
190
191     }
192
193     def 'Get a cm handle with an invalid id.'() {
194         when: 'getting cm handle details for a given cm handle id with an invalid name'
195             objectUnderTest.getNcmpServiceCmHandle('invalid cm handle with spaces')
196         then: 'an exception is thrown'
197             thrown(DataValidationException)
198         and: 'the yang model cm handle retriever is not invoked'
199             0 * mockInventoryPersistence.getYangModelCmHandle(*_)
200     }
201
202     def 'Get cm handle public properties'() {
203         given: 'a yang modelled cm handle'
204             def dmiProperties = [new YangModelCmHandle.Property('prop', 'some DMI property')]
205             def publicProperties = [new YangModelCmHandle.Property('public prop', 'some public prop')]
206             def yangModelCmHandle = new YangModelCmHandle(id:'some-cm-handle', dmiServiceName: 'some service name', dmiProperties: dmiProperties, publicProperties: publicProperties)
207         and: 'the system returns this yang modelled cm handle'
208             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
209         when: 'getting cm handle public properties for a given cm handle id from ncmp service'
210             def result = objectUnderTest.getCmHandlePublicProperties('some-cm-handle')
211         then: 'the result returns the correct data'
212             result == [ 'public prop' : 'some public prop' ]
213     }
214
215     def 'Get cm handle public properties with an invalid id.'() {
216         when: 'getting cm handle public properties for a given cm handle id with an invalid name'
217             objectUnderTest.getCmHandlePublicProperties('invalid cm handle with spaces')
218         then: 'an exception is thrown'
219             thrown(DataValidationException)
220         and: 'the yang model cm handle retriever is not invoked'
221             0 * mockInventoryPersistence.getYangModelCmHandle(*_)
222     }
223
224     def 'Get cm handle composite state'() {
225         given: 'a yang modelled cm handle'
226             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
227                 lockReason: CompositeState.LockReason.builder().lockReasonCategory(LockReasonCategory.LOCKED_MODULE_SYNC_FAILED).details("lock details").build(),
228                 lastUpdateTime: 'some-timestamp',
229                 dataSyncEnabled: false,
230                 dataStores: dataStores())
231             def dmiProperties = [new YangModelCmHandle.Property('prop', 'some DMI property')]
232             def publicProperties = [new YangModelCmHandle.Property('public prop', 'some public prop')]
233             def yangModelCmHandle = new YangModelCmHandle(id:'some-cm-handle', dmiServiceName: 'some service name', dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
234         and: 'the system returns this yang modelled cm handle'
235             1 * mockInventoryPersistence.getYangModelCmHandle('some-cm-handle') >> yangModelCmHandle
236         when: 'getting cm handle composite state for a given cm handle id from ncmp service'
237             def result = objectUnderTest.getCmHandleCompositeState('some-cm-handle')
238         then: 'the result returns the correct data'
239             result == compositeState
240     }
241
242     def 'Get cm handle composite state with an invalid id.'() {
243         when: 'getting cm handle composite state for a given cm handle id with an invalid name'
244             objectUnderTest.getCmHandleCompositeState('invalid cm handle with spaces')
245         then: 'an exception is thrown'
246             thrown(DataValidationException)
247         and: 'the yang model cm handle retriever is not invoked'
248             0 * mockInventoryPersistence.getYangModelCmHandle(_)
249     }
250
251     def 'Update resource data for pass-through running from dmi using POST #scenario DMI properties.'() {
252         given: 'cpsDataService returns valid datanode'
253             mockCpsDataService.getDataNode('NCMP-Admin', 'ncmp-dmi-registry',
254                 cmHandleXPath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode
255         when: 'get resource data is called'
256             objectUnderTest.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
257                 'testResourceId', UPDATE,
258                 '{some-json}', 'application/json')
259         then: 'DMI called with correct data'
260             1 * mockDmiDataOperations.writeResourceDataPassThroughRunningFromDmi('testCmHandle', 'testResourceId',
261                 UPDATE, '{some-json}', 'application/json')
262                 >> { new ResponseEntity<>(HttpStatus.OK) }
263     }
264
265     def 'Verify modules and create anchor params'() {
266         given: 'dmi plugin registration return created cm handles'
267             def dmiPluginRegistration = new DmiPluginRegistration(dmiPlugin: 'service1', dmiModelPlugin: 'service1',
268                 dmiDataPlugin: 'service2')
269             dmiPluginRegistration.createdCmHandles = [ncmpServiceCmHandle]
270             mockDmiPluginRegistration.getCreatedCmHandles() >> [ncmpServiceCmHandle]
271         when: 'parse and create cm handle in dmi registration then sync module'
272             objectUnderTest.parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(mockDmiPluginRegistration)
273         then: 'validate params for creating anchor and list elements'
274             1 * mockInventoryPersistence.saveListElements(_) >> {
275                 args -> {
276                     assert args[0].startsWith('{"cm-handles":[{"id":"some-cm-handle-id","state":{"cm-handle-state":"ADVISED","last-update-time":"20')
277                 }
278             }
279     }
280
281     def 'Execute cm handle id search'() {
282         given: 'valid CmHandleQueryApiParameters input'
283             def cmHandleQueryApiParameters = new CmHandleQueryApiParameters()
284             def conditionApiProperties = new ConditionApiProperties()
285             conditionApiProperties.conditionName = 'hasAllModules'
286             conditionApiProperties.conditionParameters = [[moduleName: 'module-name-1']]
287             cmHandleQueryApiParameters.cmHandleQueryParameters = [conditionApiProperties]
288         and: 'query cm handle method return with a data node list'
289             mockCpsCmHandlerQueryService.queryCmHandleIds(
290                     spiedJsonObjectMapper.convertToValueType(cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class))
291                     >> ['cm-handle-id-1']
292         when: 'execute cm handle search is called'
293             def result = objectUnderTest.executeCmHandleIdSearch(cmHandleQueryApiParameters)
294         then: 'result is the same collection as returned by the CPS Data Service'
295             assert result == ['cm-handle-id-1'] as Set
296     }
297
298     def 'Getting module definitions.'() {
299         when: 'get module definitions method is called with a valid cm handle ID'
300             objectUnderTest.getModuleDefinitionsByCmHandleId('some-cm-handle')
301         then: 'CPS module services is invoked once'
302             1 * mockInventoryPersistence.getModuleDefinitionsByCmHandleId('some-cm-handle')
303     }
304
305
306     def dataStores() {
307         CompositeState.DataStores.builder()
308                 .operationalDataStore(CompositeState.Operational.builder()
309                         .dataStoreSyncState(DataStoreSyncState.NONE_REQUESTED)
310                         .lastSyncTime('some-timestamp').build()).build()
311     }
312
313     def 'Execute cm handle search'() {
314         given: 'valid CmHandleQueryApiParameters input'
315             def cmHandleQueryApiParameters = new CmHandleQueryApiParameters()
316             def conditionApiProperties = new ConditionApiProperties()
317             conditionApiProperties.conditionName = 'hasAllModules'
318             conditionApiProperties.conditionParameters = [[moduleName: 'module-name-1']]
319             cmHandleQueryApiParameters.cmHandleQueryParameters = [conditionApiProperties]
320         and: 'query cm handle method return with a data node list'
321             mockCpsCmHandlerQueryService.queryCmHandles(
322                     spiedJsonObjectMapper.convertToValueType(cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class))
323                     >> [new NcmpServiceCmHandle(cmHandleId: 'cm-handle-id-1')]
324         when: 'execute cm handle search is called'
325             def result = objectUnderTest.executeCmHandleSearch(cmHandleQueryApiParameters)
326         then: 'result is the same collection as returned by the CPS Data Service'
327             assert result.stream().map(d -> d.cmHandleId).collect(Collectors.toSet()) == ['cm-handle-id-1'] as Set
328     }
329 }