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