Get Data under anchor using single root
[cps.git] / cps-rest / src / test / groovy / org / onap / cps / rest / controller / DataRestControllerSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Pantheon.tech
5  *  Modifications Copyright (C) 2021 Bell Canada.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.rest.controller
23
24 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
25 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
26 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
27 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
28 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
29 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
30
31 import org.modelmapper.ModelMapper
32 import org.onap.cps.api.CpsAdminService
33 import org.onap.cps.api.CpsDataService
34 import org.onap.cps.api.CpsModuleService
35 import org.onap.cps.api.CpsQueryService
36 import org.onap.cps.spi.exceptions.AlreadyDefinedException
37 import org.onap.cps.spi.exceptions.AnchorNotFoundException
38 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
39 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
40 import org.onap.cps.spi.model.DataNode
41 import org.onap.cps.spi.model.DataNodeBuilder
42 import org.spockframework.spring.SpringBean
43 import org.springframework.beans.factory.annotation.Autowired
44 import org.springframework.beans.factory.annotation.Value
45 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
46 import org.springframework.http.HttpStatus
47 import org.springframework.http.MediaType
48 import org.springframework.test.web.servlet.MockMvc
49 import spock.lang.Shared
50 import spock.lang.Specification
51 import spock.lang.Unroll
52
53 @WebMvcTest
54 class DataRestControllerSpec extends Specification {
55
56     @SpringBean
57     CpsDataService mockCpsDataService = Mock()
58
59     @SpringBean
60     CpsModuleService mockCpsModuleService = Mock()
61
62     @SpringBean
63     CpsAdminService mockCpsAdminService = Mock()
64
65     @SpringBean
66     CpsQueryService mockCpsQueryService = Mock()
67
68     @SpringBean
69     ModelMapper modelMapper = Mock()
70
71     @Autowired
72     MockMvc mvc
73
74     @Value('${rest.api.cps-base-path}')
75     def basePath
76
77     def dataNodeBaseEndpoint
78     def dataspaceName = 'my_dataspace'
79     def anchorName = 'my_anchor'
80
81     @Shared
82     static DataNode dataNodeWithLeavesNoChildren = new DataNodeBuilder().withXpath('/xpath')
83             .withLeaves([leaf: 'value', leafList: ['leaveListElement1', 'leaveListElement2']]).build()
84
85     @Shared
86     static DataNode dataNodeWithChild = new DataNodeBuilder().withXpath('/parent')
87             .withChildDataNodes([new DataNodeBuilder().withXpath("/parent/child").build()]).build()
88
89     def setup() {
90         dataNodeBaseEndpoint = "$basePath/v1/dataspaces/$dataspaceName"
91     }
92
93     @Unroll
94     def 'Create a node: #scenario.'() {
95         given: 'some json to create a data node'
96             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
97             def json = 'some json (this is not validated)'
98         when: 'post is invoked with datanode endpoint and json'
99             def response =
100                     mvc.perform(
101                             post(endpoint)
102                                     .contentType(MediaType.APPLICATION_JSON)
103                                     .param('xpath', parentNodeXpath)
104                                     .content(json)
105                     ).andReturn().response
106         then: 'a created response is returned'
107             response.status == HttpStatus.CREATED.value()
108         then: 'the java API was called with the correct parameters'
109             1 * mockCpsDataService.saveData(dataspaceName, anchorName, json)
110         where: 'following xpath parameters are are used'
111             scenario                     | parentNodeXpath
112             'no xpath parameter'         | ''
113             'xpath parameter point root' | '/'
114     }
115
116     def 'Create a child node'() {
117         given: 'some json to create a data node'
118             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
119             def json = 'some json (this is not validated)'
120         and: 'parent node xpath'
121             def parentNodeXpath = 'some xpath'
122         when: 'post is invoked with datanode endpoint and json'
123             def response =
124                     mvc.perform(
125                             post(endpoint)
126                                     .contentType(MediaType.APPLICATION_JSON)
127                                     .param('xpath', parentNodeXpath)
128                                     .content(json)
129                     ).andReturn().response
130         then: 'a created response is returned'
131             response.status == HttpStatus.CREATED.value()
132         then: 'the java API was called with the correct parameters'
133             1 * mockCpsDataService.saveData(dataspaceName, anchorName, parentNodeXpath, json)
134     }
135
136     @Unroll
137     def 'Get data node with leaves'() {
138         given: 'the service returns data node leaves'
139             def xpath = 'some xPath'
140             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
141             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS) >> dataNodeWithLeavesNoChildren
142         when: 'get request is performed through REST API'
143             def response =
144                     mvc.perform(get(endpoint).param('xpath', xpath))
145                             .andReturn().response
146         then: 'a success response is returned'
147             response.status == HttpStatus.OK.value()
148         and: 'response contains expected leaf and value'
149             response.contentAsString.contains('"leaf":"value"')
150         and: 'response contains expected leaf-list and values'
151             response.contentAsString.contains('"leafList":["leaveListElement1","leaveListElement2"]')
152     }
153
154     @Unroll
155     def 'Get data node with #scenario.'() {
156         given: 'the service returns data node with #scenario'
157             def xpath = 'some xPath'
158             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
159             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, expectedCpsDataServiceOption) >> dataNode
160         when: 'get request is performed through REST API'
161             def response =
162                     mvc.perform(
163                             get(endpoint)
164                                     .param('xpath', xpath)
165                                     .param('include-descendants', includeDescendantsOption))
166                             .andReturn().response
167         then: 'a success response is returned'
168             response.status == HttpStatus.OK.value()
169         and: 'the response contains child is #expectChildInResponse'
170             response.contentAsString.contains('"child"') == expectChildInResponse
171         where:
172             scenario                    | dataNode                     | includeDescendantsOption || expectedCpsDataServiceOption | expectChildInResponse
173             'no descendants by default' | dataNodeWithLeavesNoChildren | ''                       || OMIT_DESCENDANTS             | false
174             'no descendant explicitly'  | dataNodeWithLeavesNoChildren | 'false'                  || OMIT_DESCENDANTS             | false
175             'with descendants'          | dataNodeWithChild            | 'true'                   || INCLUDE_ALL_DESCENDANTS      | true
176     }
177
178     @Unroll
179     def 'Get data node error scenario: #scenario.'() {
180         given: 'the service throws an exception'
181             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
182             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, _) >> { throw exception }
183         when: 'get request is performed through REST API'
184             def response =
185                     mvc.perform(get(endpoint).param("xpath", xpath))
186                             .andReturn().response
187         then: 'a success response is returned'
188             response.status == httpStatus.value()
189         where:
190             scenario          | xpath     | exception                                        || httpStatus
191             'no dataspace'    | '/x-path' | new DataspaceNotFoundException('')               || HttpStatus.BAD_REQUEST
192             'no anchor'       | '/x-path' | new AnchorNotFoundException('', '')              || HttpStatus.BAD_REQUEST
193             'no data'         | '/x-path' | new DataNodeNotFoundException('', '', '')        || HttpStatus.NOT_FOUND
194             'root path'       | '/'       | new DataNodeNotFoundException('', '')            || HttpStatus.NOT_FOUND
195             'already defined' | '/x-path' | new AlreadyDefinedException('', new Throwable()) || HttpStatus.CONFLICT
196     }
197
198     @Unroll
199     def 'Update data node leaves: #scenario.'() {
200         given: 'json data'
201             def jsonData = 'json data'
202             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
203         when: 'patch request is performed'
204             def response =
205                     mvc.perform(
206                             patch(endpoint)
207                                     .contentType(MediaType.APPLICATION_JSON)
208                                     .content(jsonData)
209                                     .param('xpath', xpath)
210                     ).andReturn().response
211         then: 'the service method is invoked with expected parameters'
212             1 * mockCpsDataService.updateNodeLeaves(dataspaceName, anchorName, xpathServiceParameter, jsonData)
213         and: 'response status indicates success'
214             response.status == HttpStatus.OK.value()
215         where:
216             scenario               | xpath    | xpathServiceParameter
217             'root node by default' | ''       | '/'
218             'node by parent xpath' | '/xpath' | '/xpath'
219     }
220
221     @Unroll
222     def 'Replace data node tree: #scenario.'() {
223         given: 'json data'
224             def jsonData = 'json data'
225             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
226         when: 'put request is performed'
227             def response =
228                     mvc.perform(
229                             put(endpoint)
230                                     .contentType(MediaType.APPLICATION_JSON)
231                                     .content(jsonData)
232                                     .param('xpath', xpath))
233                             .andReturn().response
234         then: 'the service method is invoked with expected parameters'
235             1 * mockCpsDataService.replaceNodeTree(dataspaceName, anchorName, xpathServiceParameter, jsonData)
236         and: 'response status indicates success'
237             response.status == HttpStatus.OK.value()
238         where:
239             scenario               | xpath    | xpathServiceParameter
240             'root node by default' | ''       | '/'
241             'node by parent xpath' | '/xpath' | '/xpath'
242     }
243 }