Support Delete operation for ds Passtrough-Running in NCMP 1/3
[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 Nordix Foundation
6  *  Modification Copyright (C) 2021 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.onap.cps.TestUtils
26 import org.onap.cps.spi.model.ModuleReference
27
28 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
29 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
30 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
32 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
33 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
34 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
35 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
36 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
37 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
38 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE
39
40 import com.google.gson.Gson
41 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
42 import org.onap.cps.spi.model.DataNodeBuilder
43 import org.spockframework.spring.SpringBean
44 import org.springframework.beans.factory.annotation.Autowired
45 import org.springframework.beans.factory.annotation.Value
46 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
47 import org.springframework.http.HttpStatus
48 import org.springframework.http.MediaType
49 import org.springframework.test.web.servlet.MockMvc
50 import spock.lang.Specification
51
52 @WebMvcTest(NetworkCmProxyController)
53 class NetworkCmProxyControllerSpec extends Specification {
54
55     @Autowired
56     MockMvc mvc
57
58     @SpringBean
59     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
60
61     @Value('${rest.api.ncmp-base-path}/v1')
62     def ncmpBasePathV1
63
64     def cmHandle = 'some handle'
65     def xpath = 'some xpath'
66
67     def 'Query data node by cps path for the given cm handle with #scenario.'() {
68         given: 'service method returns a list containing a data node'
69             def dataNode = new DataNodeBuilder().withXpath('/xpath').build()
70             def cpsPath = 'some cps-path'
71             mockNetworkCmProxyDataService.queryDataNodes(cmHandle, cpsPath, expectedCpsDataServiceOption) >> [dataNode]
72         and: 'the query endpoint'
73             def dataNodeEndpoint = "$ncmpBasePathV1/cm-handles/$cmHandle/nodes/query"
74         when: 'query data nodes API is invoked'
75             def response = mvc.perform(get(dataNodeEndpoint)
76                     .param('cps-path', cpsPath)
77                     .param('include-descendants', includeDescendantsOption))
78                     .andReturn().response
79         then: 'the response contains the the datanode in json format'
80             response.status == HttpStatus.OK.value()
81             def expectedJsonContent = new Gson().toJson(dataNode)
82             response.getContentAsString().contains(expectedJsonContent)
83         where: 'the following options for include descendants are provided in the request'
84             scenario                    | includeDescendantsOption || expectedCpsDataServiceOption
85             'no descendants by default' | ''                       || OMIT_DESCENDANTS
86             'no descendant explicitly'  | 'false'                  || OMIT_DESCENDANTS
87             'descendants'               | 'true'                   || INCLUDE_ALL_DESCENDANTS
88     }
89
90     def 'Create data node: #scenario.'() {
91         given: 'json data'
92             def jsonData = 'json data'
93         when: 'post request is performed'
94             def response = mvc.perform(
95                     post("$ncmpBasePathV1/cm-handles/$cmHandle/nodes")
96                             .contentType(MediaType.APPLICATION_JSON)
97                             .content(jsonData)
98                             .param('xpath', reqXpath)
99             ).andReturn().response
100         then: 'the service method is invoked once with expected parameters'
101             1 * mockNetworkCmProxyDataService.createDataNode(cmHandle, usedXpath, jsonData)
102         and: 'response status indicates success'
103             response.status == HttpStatus.CREATED.value()
104         where: 'following parameters were used'
105             scenario             | reqXpath || usedXpath
106             'no xpath parameter' | ''       || '/'
107             'root xpath'         | '/'      || '/'
108             'parent node xpath'  | '/xpath' || '/xpath'
109     }
110
111     def 'Add list-node elements.'() {
112         given: 'json data and parent node xpath'
113             def jsonData = 'json data'
114             def parentNodeXpath = 'parent node xpath'
115         when: 'post request is performed'
116             def response = mvc.perform(
117                     post("$ncmpBasePathV1/cm-handles/$cmHandle/list-node")
118                             .contentType(MediaType.APPLICATION_JSON)
119                             .content(jsonData)
120                             .param('xpath', parentNodeXpath)
121             ).andReturn().response
122         then: 'the service method is invoked once with expected parameters'
123             1 * mockNetworkCmProxyDataService.addListNodeElements(cmHandle, parentNodeXpath, jsonData)
124         and: 'response status indicates success'
125             response.status == HttpStatus.CREATED.value()
126     }
127
128     def 'Update data node leaves.'() {
129         given: 'json data'
130             def jsonData = 'json data'
131         and: 'the query endpoint'
132             def endpoint = "$ncmpBasePathV1/cm-handles/$cmHandle/nodes"
133         when: 'patch request is performed'
134             def response = mvc.perform(
135                     patch(endpoint)
136                             .contentType(MediaType.APPLICATION_JSON)
137                             .content(jsonData)
138                             .param('xpath', xpath)
139             ).andReturn().response
140         then: 'the service method is invoked once with expected parameters'
141             1 * mockNetworkCmProxyDataService.updateNodeLeaves(cmHandle, xpath, jsonData)
142         and: 'response status indicates success'
143             response.status == HttpStatus.OK.value()
144     }
145
146     def 'Replace data node tree.'() {
147         given: 'json data'
148             def jsonData = 'json data'
149         and: 'the query endpoint'
150             def endpoint = "$ncmpBasePathV1/cm-handles/$cmHandle/nodes"
151         when: 'put request is performed'
152             def response = mvc.perform(
153                     put(endpoint)
154                             .contentType(MediaType.APPLICATION_JSON)
155                             .content(jsonData)
156                             .param('xpath', xpath)
157             ).andReturn().response
158         then: 'the service method is invoked once with expected parameters'
159             1 * mockNetworkCmProxyDataService.replaceNodeTree(cmHandle, xpath, jsonData)
160         and: 'response status indicates success'
161             response.status == HttpStatus.OK.value()
162     }
163
164     def 'Get data node.'() {
165         given: 'the service returns a data node'
166             def xpath = 'some xpath'
167             def dataNode = new DataNodeBuilder().withXpath(xpath).withLeaves(["leaf": "value"]).build()
168             mockNetworkCmProxyDataService.getDataNode(cmHandle, xpath, OMIT_DESCENDANTS) >> dataNode
169         and: 'the query endpoint'
170             def endpoint = "$ncmpBasePathV1/cm-handles/$cmHandle/node"
171         when: 'get request is performed through REST API'
172             def response = mvc.perform(get(endpoint).param('xpath', xpath)).andReturn().response
173         then: 'a success response is returned'
174             response.status == HttpStatus.OK.value()
175         and: 'response contains expected leaf and value'
176             response.contentAsString.contains('"leaf":"value"')
177     }
178
179     def 'Get Resource Data from pass-through operational.' () {
180         given: 'resource data url'
181             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
182                     "?resourceIdentifier=parent/child&options=(a=1,b=2)"
183         when: 'get data resource request is performed'
184             def response = mvc.perform(
185                     get(getUrl)
186                             .contentType(MediaType.APPLICATION_JSON)
187                     .accept(MediaType.APPLICATION_JSON_VALUE)
188             ).andReturn().response
189         then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
190             1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
191                     'parent/child',
192                     'application/json',
193                     '(a=1,b=2)')
194         and: 'response status is Ok'
195             response.status == HttpStatus.OK.value()
196     }
197
198     def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.' () {
199         given: 'resource data url'
200             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
201                     "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
202         and: 'ncmp service returns json object'
203             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
204                     resourceIdentifier,
205                     'application/json',
206                     '(a=1,b=2)') >> '{valid-json}'
207         when: 'get data resource request is performed'
208             def response = mvc.perform(
209                     get(getUrl)
210                             .contentType(MediaType.APPLICATION_JSON)
211                             .accept(MediaType.APPLICATION_JSON_VALUE)
212             ).andReturn().response
213         then: 'response status is Ok'
214             response.status == HttpStatus.OK.value()
215         and: 'response contains valid object body'
216             response.getContentAsString() == '{valid-json}'
217         where: 'tokens are used in the resource identifier parameter'
218             scenario                       | resourceIdentifier
219             '/'                            | 'id/with/slashes'
220             '?'                            | 'idWith?'
221             ','                            | 'idWith,'
222             '='                            | 'idWith='
223             '[]'                           | 'idWith[]'
224             '? needs to be encoded as %3F' | 'idWith%3F'
225     }
226
227     def 'Update resource data from pass-through running.' () {
228         given: 'update resource data url'
229             def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
230                 "?resourceIdentifier=parent/child"
231         when: 'update data resource request is performed'
232             def response = mvc.perform(
233                 put(updateUrl)
234                     .contentType(MediaType.APPLICATION_JSON_VALUE)
235                     .accept(MediaType.APPLICATION_JSON_VALUE).content('some-request-body')
236             ).andReturn().response
237         then: 'ncmp service method to update resource is called'
238             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
239                 'parent/child', UPDATE,'some-request-body', 'application/json;charset=UTF-8')
240         and: 'the response status is OK'
241             response.status == HttpStatus.OK.value()
242     }
243
244     def 'Create Resource Data from pass-through running with #scenario.' () {
245         given: 'resource data url'
246             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
247                     "?resourceIdentifier=parent/child"
248         when: 'create resource request is performed'
249             def response = mvc.perform(
250                     post(url)
251                             .contentType(MediaType.APPLICATION_JSON_VALUE)
252                             .accept(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
253             ).andReturn().response
254         then: 'ncmp service method to create resource called'
255             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
256                 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
257         and: 'resource is created'
258             response.status == HttpStatus.CREATED.value()
259         where: 'given request body'
260             scenario                        |  requestBody
261             'body contains " and new line'  |  'body with " quote and \n new line'
262             'body contains normal string'   |  'normal request body'
263     }
264
265     def 'Get module references for the given dataspace and cm handle.' () {
266         given: 'get module references url'
267             def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
268         when: 'get module resource request is performed'
269             def response =mvc.perform(get(getUrl)).andReturn().response
270         then: 'ncmp service method to get yang resource module references is called'
271             mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
272                     >> [new ModuleReference(moduleName: 'some-name1',revision: 'some-revision1')]
273         and: 'response contains an array with the module name and revision'
274             response.getContentAsString() == '[{"moduleName":"some-name1","revision":"some-revision1"}]'
275         and: 'response returns an OK http code'
276             response.status == HttpStatus.OK.value()
277     }
278
279     def 'Retrieve cm handles.'() {
280         given: 'an endpoint and json data'
281             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
282             String jsonData = TestUtils.getResourceFileContent('cmhandle-search.json')
283         and: 'the service method is invoked with module names and returns two cm handle ids'
284             mockNetworkCmProxyDataService.executeCmHandleHasAllModulesSearch(['module1', 'module2']) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
285         when: 'the searches api is invoked'
286             def response = mvc.perform(post(searchesEndpoint)
287                     .contentType(MediaType.APPLICATION_JSON)
288                     .content(jsonData)).andReturn().response
289         then: 'response status returns OK'
290             response.status == HttpStatus.OK.value()
291         and: 'the expected response content is returned'
292             response.contentAsString == '{"cmHandles":[{"cmHandleId":"some-cmhandle-id1"},{"cmHandleId":"some-cmhandle-id2"}]}'
293     }
294
295     def 'Call execute cm handle searches with unrecognized condition name.'() {
296         given: 'an endpoint and json data'
297             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
298             String jsonData = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
299         when: 'the searches api is invoked'
300             def response = mvc.perform(post(searchesEndpoint)
301                     .contentType(MediaType.APPLICATION_JSON)
302                     .content(jsonData)).andReturn().response
303         then: 'an empty cm handle identifier is returned'
304             response.contentAsString == '{"cmHandles":[]}'
305     }
306
307     def 'Patch resource data in pass-through running datastore.' () {
308         given: 'patch resource data url'
309             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
310                     "?resourceIdentifier=parent/child"
311         when: 'patch data resource request is performed'
312             def response = mvc.perform(
313                     patch(url)
314                             .contentType(MediaType.APPLICATION_JSON)
315                             .accept(MediaType.APPLICATION_JSON).content('{"some-key" : "some-value"}')
316             ).andReturn().response
317         then: 'ncmp service method to update resource is called'
318             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
319                     'parent/child', PATCH, '{some-key=some-value}', 'application/json;charset=UTF-8')
320         and: 'the response status is OK'
321             response.status == HttpStatus.OK.value()
322     }
323
324     def 'Delete resource data in pass-through running datastore.' () {
325         given: 'delete resource data url'
326             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
327                      "?resourceIdentifier=parent/child"
328         when: 'delete data resource request is performed'
329             def response = mvc.perform(
330                 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
331                 .content('{"some-key" : "some-value"}')).andReturn().response
332         then: 'the ncmp service method to delete resource is called'
333             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
334                 'parent/child', DELETE, '{"some-key" : "some-value"}', 'application/json;charset=UTF-8')
335         and: 'the response is No Content'
336             response.status == HttpStatus.NO_CONTENT.value()
337     }
338 }
339