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