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