Data Sync Watchdog Process
[cps.git] / cps-ncmp-rest / src / test / groovy / org / onap / cps / ncmp / rest / controller / NetworkCmProxyControllerSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Modifications Copyright (C) 2021 highstreet technologies GmbH
5  *  Modifications Copyright (C) 2021-2022 Nordix Foundation
6  *  Modifications Copyright (C) 2021-2022 Bell Canada.
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.ncmp.rest.controller
25
26 import org.mapstruct.factory.Mappers
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.SyncState
30 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
31 import org.onap.cps.ncmp.rest.mapper.RestOutputCmHandleStateMapper
32 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor
33 import org.onap.cps.ncmp.rest.util.DeprecationHelper
34 import spock.lang.Shared
35
36 import java.time.OffsetDateTime
37 import java.time.ZoneOffset
38 import java.time.format.DateTimeFormatter
39
40 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
41 import static org.onap.cps.ncmp.api.inventory.CompositeState.DataStores
42 import static org.onap.cps.ncmp.api.inventory.CompositeState.Operational
43 import static org.onap.cps.ncmp.api.inventory.CompositeState.Running
44 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
45 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
46 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
47 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
48 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
49 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
50 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
51 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE
52
53 import com.fasterxml.jackson.databind.ObjectMapper
54 import org.onap.cps.TestUtils
55 import org.onap.cps.spi.model.ModuleReference
56 import org.onap.cps.utils.JsonObjectMapper
57 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
58 import org.spockframework.spring.SpringBean
59 import org.springframework.beans.factory.annotation.Autowired
60 import org.springframework.beans.factory.annotation.Value
61 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
62 import org.springframework.http.HttpStatus
63 import org.springframework.http.MediaType
64 import org.springframework.test.web.servlet.MockMvc
65 import spock.lang.Specification
66
67 @WebMvcTest(NetworkCmProxyController)
68 class NetworkCmProxyControllerSpec extends Specification {
69
70     @Autowired
71     MockMvc mvc
72
73     @SpringBean
74     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
75
76     @SpringBean
77     ObjectMapper objectMapper = new ObjectMapper()
78
79     @SpringBean
80     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(objectMapper)
81
82     @SpringBean
83     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
84
85     @SpringBean
86     RestOutputCmHandleStateMapper restOutputCmHandleStateMapper = Mappers.getMapper(RestOutputCmHandleStateMapper)
87
88     @SpringBean
89     CpsNcmpTaskExecutor spiedCpsTaskExecutor = Spy()
90
91     @SpringBean
92     DeprecationHelper stubbedDeprecationHelper = Stub()
93
94     @Value('${rest.api.ncmp-base-path}/v1')
95     def ncmpBasePathV1
96
97     def requestBody = '{"some-key":"some-value"}'
98
99     @Shared
100     def NO_TOPIC = null
101     def NO_REQUEST_ID = null
102
103     def formattedDateAndTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
104         .format(OffsetDateTime.of(2022, 12, 31, 20, 30, 40, 1, ZoneOffset.UTC))
105
106     def 'Get Resource Data from pass-through operational.'() {
107         given: 'resource data url'
108             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
109                     "?resourceIdentifier=parent/child&options=(a=1,b=2)"
110         when: 'get data resource request is performed'
111             def response = mvc.perform(
112                     get(getUrl)
113                             .contentType(MediaType.APPLICATION_JSON)
114             ).andReturn().response
115         then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
116             1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
117                     'parent/child',
118                     '(a=1,b=2)',
119                     NO_TOPIC,
120                     NO_REQUEST_ID)
121         and: 'response status is Ok'
122             response.status == HttpStatus.OK.value()
123     }
124
125     def 'Get Resource Data from #datastoreInUrl with #scenario.'() {
126         given: 'resource data url'
127             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
128                     "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
129         when: 'get data resource request is performed'
130             def response = mvc.perform(
131                     get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
132         then: 'task executor is called appropriate number of times'
133             expectedNumberOfExecutorExecutions * spiedCpsTaskExecutor.executeTask(_, 2000)
134         and: 'response status is expected'
135             response.status == HttpStatus.OK.value()
136         where: 'the following parameters are used'
137             scenario                               | datastoreInUrl            | topicQueryParam        || expectedTopicName | expectedNumberOfExecutorExecutions
138             'url with valid topic'                 | 'passthrough-operational' | '&topic=my-topic-name' || 'my-topic-name'   | 1
139             'no topic in url'                      | 'passthrough-operational' | ''                     || NO_TOPIC          | 0
140             'null topic in url'                    | 'passthrough-operational' | '&topic=null'          || 'null'            | 1
141             'url with valid topic'                 | 'passthrough-running'     | '&topic=my-topic-name' || 'my-topic-name'   | 1
142             'no topic in url'                      | 'passthrough-running'     | ''                     || NO_TOPIC          | 0
143             'null topic in url'                    | 'passthrough-running'     | '&topic=null'          || 'null'            | 1
144     }
145
146     def 'Fail to get Resource Data from #datastoreInUrl when #scenario.'() {
147         given: 'resource data url'
148             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
149                 "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
150         when: 'get data resource request is performed'
151             def response = mvc.perform(
152                 get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
153         then: 'abad request is returned'
154             response.status == HttpStatus.BAD_REQUEST.value()
155         where: 'the following parameters are used'
156             scenario                               | datastoreInUrl            | topicQueryParam
157             'empty topic in url'                   | 'passthrough-operational' | '&topic=\"\"'
158             'missing topic in url'                 | 'passthrough-operational' | '&topic='
159             'blank topic value in url'             | 'passthrough-operational' | '&topic=\" \"'
160             'invalid non-empty topic value in url' | 'passthrough-operational' | '&topic=1_5_*_#'
161             'empty topic in url'                   | 'passthrough-running'     | '&topic=\"\"'
162             'missing topic in url'                 | 'passthrough-running'     | '&topic='
163             'blank topic value in url'             | 'passthrough-running'     | '&topic=\" \"'
164             'invalid non-empty topic value in url' | 'passthrough-running'     | '&topic=1_5_*_#'
165     }
166
167     def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.'() {
168         given: 'resource data url'
169             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
170                     "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
171         and: 'ncmp service returns json object'
172             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
173                     resourceIdentifier,
174                     '(a=1,b=2)',
175                     NO_TOPIC,
176                     NO_REQUEST_ID) >> '{valid-json}'
177         when: 'get data resource request is performed'
178             def response = mvc.perform(
179                     get(getUrl)
180                             .contentType(MediaType.APPLICATION_JSON)
181             ).andReturn().response
182         then: 'response status is Ok'
183             response.status == HttpStatus.OK.value()
184         and: 'response contains valid object body'
185             response.getContentAsString() == '{valid-json}'
186         where: 'tokens are used in the resource identifier parameter'
187             scenario                       | resourceIdentifier
188             '/'                            | 'id/with/slashes'
189             '?'                            | 'idWith?'
190             ','                            | 'idWith,'
191             '='                            | 'idWith='
192             '[]'                           | 'idWith[]'
193             '? needs to be encoded as %3F' | 'idWith%3F'
194     }
195
196     def 'Update resource data from pass-through running.' () {
197         given: 'update resource data url'
198             def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
199                 "?resourceIdentifier=parent/child"
200         when: 'update data resource request is performed'
201             def response = mvc.perform(
202                 put(updateUrl)
203                     .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
204             ).andReturn().response
205         then: 'ncmp service method to update resource is called'
206             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
207                 'parent/child', UPDATE, requestBody, 'application/json;charset=UTF-8')
208         and: 'the response status is OK'
209             response.status == HttpStatus.OK.value()
210     }
211
212     def 'Create Resource Data from pass-through running with #scenario.' () {
213         given: 'resource data url'
214             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
215                     "?resourceIdentifier=parent/child"
216             def requestBody = '{"some-key":"some-value"}'
217         when: 'create resource request is performed'
218             def response = mvc.perform(
219                     post(url)
220                             .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
221             ).andReturn().response
222         then: 'ncmp service method to create resource called'
223             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
224                 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
225         and: 'resource is created'
226             response.status == HttpStatus.CREATED.value()
227     }
228
229     def 'Get module references for the given dataspace and cm handle.' () {
230         given: 'get module references url'
231             def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
232         when: 'get module resource request is performed'
233             def response =mvc.perform(get(getUrl)).andReturn().response
234         then: 'ncmp service method to get yang resource module references is called'
235             mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
236                     >> [new ModuleReference(moduleName: 'some-name1',revision: '2021-10-03')]
237         and: 'response contains an array with the module name and revision'
238             response.getContentAsString() == '[{"moduleName":"some-name1","revision":"2021-10-03"}]'
239         and: 'response returns an OK http code'
240             response.status == HttpStatus.OK.value()
241     }
242
243     def 'Retrieve cm handles.'() {
244         given: 'an endpoint and json data'
245             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
246             String jsonString = TestUtils.getResourceFileContent('cmhandle-search.json')
247         and: 'the service method is invoked with module names and returns two cm handles'
248             def cmHandle1 = new NcmpServiceCmHandle()
249             cmHandle1.cmHandleId = 'some-cmhandle-id1'
250             cmHandle1.publicProperties = [color:'yellow']
251             def cmHandle2 = new NcmpServiceCmHandle()
252             cmHandle2.cmHandleId = 'some-cmhandle-id2'
253             cmHandle2.publicProperties = [color:'green']
254             mockNetworkCmProxyDataService.executeCmHandleSearch(_) >> [cmHandle1, cmHandle2]
255         when: 'the searches api is invoked'
256             def response = mvc.perform(post(searchesEndpoint)
257                     .contentType(MediaType.APPLICATION_JSON)
258                     .content(jsonString)).andReturn().response
259         then: 'response status returns OK'
260             response.status == HttpStatus.OK.value()
261         and: 'the expected response content is returned'
262             response.contentAsString == '[{"cmHandle":"some-cmhandle-id1","publicCmHandleProperties":[{"color":"yellow"}],"state":null},{"cmHandle":"some-cmhandle-id2","publicCmHandleProperties":[{"color":"green"}],"state":null}]'
263     }
264
265     def 'Get Cm Handle details by Cm Handle id.'() {
266         given: 'an endpoint and a cm handle'
267             def cmHandleDetailsEndpoint = "$ncmpBasePathV1/ch/some-cm-handle"
268         and: 'an existing ncmp service cm handle'
269             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
270                 lastUpdateTime: formattedDateAndTime.toString(),
271                 dataStores: dataStores())
272             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle', compositeState: compositeState)
273         and: 'the service method is invoked with the cm handle id'
274             1 * mockNetworkCmProxyDataService.getNcmpServiceCmHandle('some-cm-handle') >> ncmpServiceCmHandle
275         when: 'the cm handle details api is invoked'
276             def response = mvc.perform(get(cmHandleDetailsEndpoint)).andReturn().response
277         then: 'the correct response is returned'
278             response.status == HttpStatus.OK.value()
279         and: 'the response returns the correct state and timestamp'
280             response.contentAsString.contains('some-cm-handle')
281             response.contentAsString.contains('ADVISED')
282             response.contentAsString.contains('2022-12-31T20:30:40.000+0000')
283     }
284
285     def 'Get Cm Handle public properties by Cm Handle id.' () {
286         given: 'a cm handle properties endpoint'
287             def cmHandlePropertiesEndpoint = "$ncmpBasePathV1/ch/some-cm-handle/properties"
288         and: 'some cm handle public properties'
289             def publicProperties =  [ 'public prop':'some public property' ]
290         and: 'the service method is invoked with the cm handle id returning the cm handle public properties'
291             1 * mockNetworkCmProxyDataService.getCmHandlePublicProperties('some-cm-handle') >> publicProperties
292         when: 'the cm handle properties api is invoked'
293             def response = mvc.perform(get(cmHandlePropertiesEndpoint)).andReturn().response
294         then: 'the correct response is returned'
295             response.status == HttpStatus.OK.value()
296         and: 'the response returns public properties and the correct properties'
297             response.contentAsString.equals('{"publicCmHandleProperties":[{"public prop":"some public property"}]}')
298     }
299
300     def 'Call execute cm handle searches with unrecognized condition name.'() {
301         given: 'an endpoint and json data'
302             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
303             String jsonString = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
304         and: 'the service method is invoked with module names and returns two cm handles'
305             def cmHandel1 = new NcmpServiceCmHandle()
306             cmHandel1.cmHandleId = 'some-cmhandle-id1'
307             cmHandel1.publicProperties = [color:'yellow']
308             def cmHandel2 = new NcmpServiceCmHandle()
309             cmHandel2.cmHandleId = 'some-cmhandle-id2'
310             cmHandel2.publicProperties = [color:'green']
311             mockNetworkCmProxyDataService.executeCmHandleSearch(_) >> [cmHandel1, cmHandel2]
312         when: 'the searches api is invoked'
313             def response = mvc.perform(post(searchesEndpoint)
314                     .contentType(MediaType.APPLICATION_JSON)
315                     .content(jsonString)).andReturn().response
316         then: 'an empty cm handle identifier is returned'
317             response.contentAsString == '[{"cmHandle":"some-cmhandle-id1","publicCmHandleProperties":[{"color":"yellow"}],"state":null},{"cmHandle":"some-cmhandle-id2","publicCmHandleProperties":[{"color":"green"}],"state":null}]'
318     }
319
320     def 'Query for cm handles matching query parameters'() {
321         given: 'an endpoint and json data'
322             def searchesEndpoint = "$ncmpBasePathV1/ch/id-searches"
323         and: 'the service method is invoked with module names and returns cm handle ids'
324             1 * mockNetworkCmProxyDataService.executeCmHandleIdSearch(_) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
325         when: 'the searches api is invoked'
326             def response = mvc.perform(post(searchesEndpoint)
327                 .contentType(MediaType.APPLICATION_JSON)
328                 .content('{}')).andReturn().response
329         then: 'cm handle ids are returned'
330             response.contentAsString == '["some-cmhandle-id1","some-cmhandle-id2"]'
331     }
332
333     def 'Query for cm handles with invalid request payload'() {
334         when: 'the searches api is invoked'
335             def searchesEndpoint = "$ncmpBasePathV1/ch/id-searches"
336             def invalidInputData = '{invalidJson}'
337             def response = mvc.perform(post(searchesEndpoint)
338                     .contentType(MediaType.APPLICATION_JSON)
339                     .content(invalidInputData)).andReturn().response
340         then: 'BAD_REQUEST is returned'
341             response.getStatus() == 400
342     }
343
344     def 'Patch resource data in pass-through running datastore.' () {
345         given: 'patch resource data url'
346             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
347                     "?resourceIdentifier=parent/child"
348         when: 'patch data resource request is performed'
349             def response = mvc.perform(
350                     patch(url)
351                             .contentType(MediaType.APPLICATION_JSON)
352                             .accept(MediaType.APPLICATION_JSON).content(requestBody)
353             ).andReturn().response
354         then: 'ncmp service method to update resource is called'
355             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
356                     'parent/child', PATCH, requestBody, 'application/json;charset=UTF-8')
357         and: 'the response status is OK'
358             response.status == HttpStatus.OK.value()
359     }
360
361     def 'Delete resource data in pass-through running datastore.' () {
362         given: 'delete resource data url'
363             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
364                      "?resourceIdentifier=parent/child"
365         when: 'delete data resource request is performed'
366             def response = mvc.perform(
367                 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn().response
368         then: 'the ncmp service method to delete resource is called (with null as body)'
369             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
370                 'parent/child', DELETE, null, 'application/json;charset=UTF-8')
371         and: 'the response is No Content'
372             response.status == HttpStatus.NO_CONTENT.value()
373     }
374
375     def 'Get resource data from DMI with valid topic i.e. async request for #scenario'() {
376         given: 'resource data url'
377             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
378                     "?resourceIdentifier=parent/child&options=(a=1,b=2)&topic=my-topic-name"
379         when: 'get data resource request is performed'
380             def response = mvc.perform(
381                     get(getUrl)
382                             .contentType(MediaType.APPLICATION_JSON)
383                             .accept(MediaType.APPLICATION_JSON_VALUE)
384             ).andReturn().response
385         then: 'async request id is generated'
386             assert response.contentAsString.contains("requestId")
387         where: 'the following parameters are used'
388             scenario                   | datastoreInUrl
389             ':passthrough-operational' | 'passthrough-operational'
390             ':passthrough-running'     | 'passthrough-running'
391     }
392
393     def dataStores() {
394         DataStores.builder()
395             .operationalDataStore(Operational.builder()
396                 .syncState(SyncState.NONE_REQUESTED)
397                 .lastSyncTime(formattedDateAndTime.toString()).build()).build()
398     }
399
400 }
401