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