Async: NCMP Rest impl. including Request ID generation
[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  *  Modification Copyright (C) 2021 highstreet technologies GmbH
5  *  Modification Copyright (C) 2021-2022 Nordix Foundation
6  *  Modification 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  *  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.rest.controller
24
25 import org.mapstruct.factory.Mappers
26 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
27 import spock.lang.Shared
28
29 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
30 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
32 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
33 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
34 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
35 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
36 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
37 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE
38
39 import com.fasterxml.jackson.databind.ObjectMapper
40 import org.onap.cps.TestUtils
41 import org.onap.cps.spi.model.ModuleReference
42 import org.onap.cps.utils.JsonObjectMapper
43 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
44 import org.spockframework.spring.SpringBean
45 import org.springframework.beans.factory.annotation.Autowired
46 import org.springframework.beans.factory.annotation.Value
47 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
48 import org.springframework.http.HttpStatus
49 import org.springframework.http.MediaType
50 import org.springframework.test.web.servlet.MockMvc
51 import spock.lang.Specification
52
53 @WebMvcTest(NetworkCmProxyController)
54 class NetworkCmProxyControllerSpec extends Specification {
55
56     @Autowired
57     MockMvc mvc
58
59     @SpringBean
60     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
61
62     @SpringBean
63     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
64
65     @SpringBean
66     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
67
68     @Value('${rest.api.ncmp-base-path}/v1')
69     def ncmpBasePathV1
70
71     def requestBody = '{"some-key":"some-value"}'
72
73     @Shared
74     def NO_TOPIC = null
75     def NO_REQUEST_ID = null
76
77     def 'Get Resource Data from pass-through operational.'() {
78         given: 'resource data url'
79             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
80                     "?resourceIdentifier=parent/child&options=(a=1,b=2)"
81         when: 'get data resource request is performed'
82             def response = mvc.perform(
83                     get(getUrl)
84                             .contentType(MediaType.APPLICATION_JSON)
85             ).andReturn().response
86         then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
87             1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
88                     'parent/child',
89                     '(a=1,b=2)',
90                     NO_TOPIC,
91                     NO_REQUEST_ID)
92         and: 'response status is Ok'
93             response.status == HttpStatus.OK.value()
94     }
95
96     def 'Get Resource Data from #datastoreInUrl with #scenario.'() {
97         given: 'resource data url'
98             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
99                     "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
100         when: 'get data resource request is performed'
101             def response = mvc.perform(
102                     get(getUrl)
103                     .contentType(MediaType.APPLICATION_JSON)
104             ).andReturn().response
105         then: 'the NCMP data service is called with operational data for cm handle'
106             expectedNumberOfMethodExecutions
107                     * mockNetworkCmProxyDataService."${expectedMethodName}"('testCmHandle',
108                     'parent/child',
109                     '(a=1,b=2)',
110                     expectedTopicName,
111                     _)
112         then: 'response status is expected'
113             response.status == expectedHttpStatus
114         where: 'the following parameters are used'
115             scenario                               | datastoreInUrl            | topicQueryParam        || expectedTopicName | expectedMethodName                             | expectedNumberOfMethodExecutions | expectedHttpStatus
116             'url with valid topic'                 | 'passthrough-operational' | '&topic=my-topic-name' || 'my-topic-name'   | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
117             'no topic in url'                      | 'passthrough-operational' | ''                     || NO_TOPIC          | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
118             'null topic in url'                    | 'passthrough-operational' | '&topic=null'          || 'null'            | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
119             'empty topic in url'                   | 'passthrough-operational' | '&topic=\"\"'          || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
120             'missing topic in url'                 | 'passthrough-operational' | '&topic='              || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
121             'blank topic value in url'             | 'passthrough-operational' | '&topic=\" \"'         || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
122             'invalid non-empty topic value in url' | 'passthrough-operational' | '&topic=1_5_*_#'       || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
123             'url with valid topic'                 | 'passthrough-running'     | '&topic=my-topic-name' || 'my-topic-name'   | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
124             'no topic in url'                      | 'passthrough-running'     | ''                     || NO_TOPIC          | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
125             'null topic in url'                    | 'passthrough-running'     | '&topic=null'          || 'null'            | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
126             'empty topic in url'                   | 'passthrough-running'     | '&topic=\"\"'          || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
127             'missing topic in url'                 | 'passthrough-running'     | '&topic='              || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
128             'blank topic value in url'             | 'passthrough-running'     | '&topic=\" \"'         || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
129             'invalid non-empty topic value in url' | 'passthrough-running'     | '&topic=1_5_*_#'       || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
130     }
131
132     def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.'() {
133         given: 'resource data url'
134             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
135                     "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
136         and: 'ncmp service returns json object'
137             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
138                     resourceIdentifier,
139                     '(a=1,b=2)',
140                     NO_TOPIC,
141                     NO_REQUEST_ID) >> '{valid-json}'
142         when: 'get data resource request is performed'
143             def response = mvc.perform(
144                     get(getUrl)
145                             .contentType(MediaType.APPLICATION_JSON)
146             ).andReturn().response
147         then: 'response status is Ok'
148             response.status == HttpStatus.OK.value()
149         and: 'response contains valid object body'
150             response.getContentAsString() == '{valid-json}'
151         where: 'tokens are used in the resource identifier parameter'
152             scenario                       | resourceIdentifier
153             '/'                            | 'id/with/slashes'
154             '?'                            | 'idWith?'
155             ','                            | 'idWith,'
156             '='                            | 'idWith='
157             '[]'                           | 'idWith[]'
158             '? needs to be encoded as %3F' | 'idWith%3F'
159     }
160
161     def 'Update resource data from pass-through running.' () {
162         given: 'update resource data url'
163             def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
164                 "?resourceIdentifier=parent/child"
165         when: 'update data resource request is performed'
166             def response = mvc.perform(
167                 put(updateUrl)
168                     .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
169             ).andReturn().response
170         then: 'ncmp service method to update resource is called'
171             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
172                 'parent/child', UPDATE, requestBody, 'application/json;charset=UTF-8')
173         and: 'the response status is OK'
174             response.status == HttpStatus.OK.value()
175     }
176
177     def 'Create Resource Data from pass-through running with #scenario.' () {
178         given: 'resource data url'
179             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
180                     "?resourceIdentifier=parent/child"
181             def requestBody = '{"some-key":"some-value"}'
182         when: 'create resource request is performed'
183             def response = mvc.perform(
184                     post(url)
185                             .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
186             ).andReturn().response
187         then: 'ncmp service method to create resource called'
188             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
189                 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
190         and: 'resource is created'
191             response.status == HttpStatus.CREATED.value()
192     }
193
194     def 'Get module references for the given dataspace and cm handle.' () {
195         given: 'get module references url'
196             def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
197         when: 'get module resource request is performed'
198             def response =mvc.perform(get(getUrl)).andReturn().response
199         then: 'ncmp service method to get yang resource module references is called'
200             mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
201                     >> [new ModuleReference(moduleName: 'some-name1',revision: '2021-10-03')]
202         and: 'response contains an array with the module name and revision'
203             response.getContentAsString() == '[{"moduleName":"some-name1","revision":"2021-10-03"}]'
204         and: 'response returns an OK http code'
205             response.status == HttpStatus.OK.value()
206     }
207
208     def 'Retrieve cm handles.'() {
209         given: 'an endpoint and json data'
210             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
211             String jsonString = TestUtils.getResourceFileContent('cmhandle-search.json')
212         and: 'the service method is invoked with module names and returns two cm handle ids'
213             mockNetworkCmProxyDataService.executeCmHandleHasAllModulesSearch(['module1', 'module2']) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
214         when: 'the searches api is invoked'
215             def response = mvc.perform(post(searchesEndpoint)
216                     .contentType(MediaType.APPLICATION_JSON)
217                     .content(jsonString)).andReturn().response
218         then: 'response status returns OK'
219             response.status == HttpStatus.OK.value()
220         and: 'the expected response content is returned'
221             response.contentAsString == '{"cmHandles":[{"cmHandleId":"some-cmhandle-id1"},{"cmHandleId":"some-cmhandle-id2"}]}'
222     }
223
224     def 'Get Cm Handle details by Cm Handle id.' () {
225         given: 'an endpoint and a cm handle'
226             def cmHandleDetailsEndpoint = "$ncmpBasePathV1/ch/Some-Cm-Handle"
227         and: 'an existing ncmp service cm handle'
228             def cmHandleId = 'Some-Cm-Handle'
229             def dmiProperties = [ prop:'some DMI property' ]
230             def publicProperties = [ "public prop":'some public property' ]
231             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleID: cmHandleId, dmiProperties: dmiProperties, publicProperties: publicProperties)
232         and: 'the service method is invoked with the cm handle id'
233             1 * mockNetworkCmProxyDataService.getNcmpServiceCmHandle('Some-Cm-Handle') >> ncmpServiceCmHandle
234         when: 'the cm handle details api is invoked'
235             def response = mvc.perform(get(cmHandleDetailsEndpoint)).andReturn().response
236         then: 'the correct response is returned'
237             response.status == HttpStatus.OK.value()
238         and: 'the response returns public properties and the correct properties'
239             response.contentAsString.contains('publicCmHandleProperties')
240             response.contentAsString.contains('public prop')
241             response.contentAsString.contains('some public property')
242         and: 'the content does not contain dmi properties'
243             !response.contentAsString.contains("some DMI property")
244     }
245
246     def 'Call execute cm handle searches with unrecognized condition name.'() {
247         given: 'an endpoint and json data'
248             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
249             String jsonString = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
250         when: 'the searches api is invoked'
251             def response = mvc.perform(post(searchesEndpoint)
252                     .contentType(MediaType.APPLICATION_JSON)
253                     .content(jsonString)).andReturn().response
254         then: 'an empty cm handle identifier is returned'
255             response.contentAsString == '{"cmHandles":[]}'
256     }
257
258     def 'Patch resource data in pass-through running datastore.' () {
259         given: 'patch resource data url'
260             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
261                     "?resourceIdentifier=parent/child"
262         when: 'patch data resource request is performed'
263             def response = mvc.perform(
264                     patch(url)
265                             .contentType(MediaType.APPLICATION_JSON)
266                             .accept(MediaType.APPLICATION_JSON).content(requestBody)
267             ).andReturn().response
268         then: 'ncmp service method to update resource is called'
269             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
270                     'parent/child', PATCH, requestBody, 'application/json;charset=UTF-8')
271         and: 'the response status is OK'
272             response.status == HttpStatus.OK.value()
273     }
274
275     def 'Delete resource data in pass-through running datastore.' () {
276         given: 'delete resource data url'
277             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
278                      "?resourceIdentifier=parent/child"
279         when: 'delete data resource request is performed'
280             def response = mvc.perform(
281                 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn().response
282         then: 'the ncmp service method to delete resource is called (with null as body)'
283             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
284                 'parent/child', DELETE, null, 'application/json;charset=UTF-8')
285         and: 'the response is No Content'
286             response.status == HttpStatus.NO_CONTENT.value()
287     }
288
289     def 'Get resource data from DMI with valid topic i.e. async request for #scenario'() {
290         given: 'resource data url'
291             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
292                     "?resourceIdentifier=parent/child&options=(a=1,b=2)&topic=my-topic-name"
293         when: 'get data resource request is performed'
294             def response = mvc.perform(
295                     get(getUrl)
296                             .contentType(MediaType.APPLICATION_JSON)
297                             .accept(MediaType.APPLICATION_JSON_VALUE)
298             ).andReturn().response
299         then: 'async request id is generated'
300             assert response.contentAsString.contains("requestId")
301         where: 'the following parameters are used'
302             scenario                   | datastoreInUrl
303             ':passthrough-operational' | 'passthrough-operational'
304             ':passthrough-running'     | 'passthrough-running'
305     }
306
307 }
308