Internal Server Error when creating the same data node twice
[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     def 'Create a node.'() {
94         given: 'some json to create a data node'
95             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
96             def json = 'some json (this is not validated)'
97         when: 'post is invoked with datanode endpoint and json'
98             def response =
99                     mvc.perform(
100                             post(endpoint)
101                                     .contentType(MediaType.APPLICATION_JSON).content(json))
102                             .andReturn().response
103         then: 'a created response is returned'
104             response.status == HttpStatus.CREATED.value()
105         then: 'the java API was called with the correct parameters'
106             1 * mockCpsDataService.saveData(dataspaceName, anchorName, json)
107     }
108
109     @Unroll
110     def 'Get data node with leaves'() {
111         given: 'the service returns data node leaves'
112             def xpath = 'some xPath'
113             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
114             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS) >> dataNodeWithLeavesNoChildren
115         when: 'get request is performed through REST API'
116             def response =
117                     mvc.perform(get(endpoint).param('xpath', xpath))
118                             .andReturn().response
119         then: 'a success response is returned'
120             response.status == HttpStatus.OK.value()
121         and: 'response contains expected leaf and value'
122             response.contentAsString.contains('"leaf":"value"')
123         and: 'response contains expected leaf-list and values'
124             response.contentAsString.contains('"leafList":["leaveListElement1","leaveListElement2"]')
125     }
126
127     @Unroll
128     def 'Get data node with #scenario.'() {
129         given: 'the service returns data node with #scenario'
130             def xpath = 'some xPath'
131             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
132             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, expectedCpsDataServiceOption) >> dataNode
133         when: 'get request is performed through REST API'
134             def response =
135                     mvc.perform(
136                             get(endpoint)
137                                     .param('xpath', xpath)
138                                     .param('include-descendants', includeDescendantsOption))
139                             .andReturn().response
140         then: 'a success response is returned'
141             response.status == HttpStatus.OK.value()
142         and: 'the response contains child is #expectChildInResponse'
143             response.contentAsString.contains('"child"') == expectChildInResponse
144         where:
145             scenario                    | dataNode                     | includeDescendantsOption || expectedCpsDataServiceOption | expectChildInResponse
146             'no descendants by default' | dataNodeWithLeavesNoChildren | ''                       || OMIT_DESCENDANTS             | false
147             'no descendant explicitly'  | dataNodeWithLeavesNoChildren | 'false'                  || OMIT_DESCENDANTS             | false
148             'with descendants'          | dataNodeWithChild            | 'true'                   || INCLUDE_ALL_DESCENDANTS      | true
149     }
150
151     @Unroll
152     def 'Get data node error scenario: #scenario.'() {
153         given: 'the service throws an exception'
154             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/node"
155             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, _) >> { throw exception }
156         when: 'get request is performed through REST API'
157             def response =
158                     mvc.perform(get(endpoint).param("xpath", xpath))
159                             .andReturn().response
160         then: 'a success response is returned'
161             response.status == httpStatus.value()
162         where:
163             scenario          | xpath     | exception                                 || httpStatus
164             'no dataspace'    | '/x-path' | new DataspaceNotFoundException('')        || HttpStatus.BAD_REQUEST
165             'no anchor'       | '/x-path' | new AnchorNotFoundException('', '')       || HttpStatus.BAD_REQUEST
166             'no data'         | '/x-path' | new DataNodeNotFoundException('', '', '') || HttpStatus.NOT_FOUND
167             'empty path'      | ''        | new IllegalStateException()               || HttpStatus.NOT_IMPLEMENTED
168             'already defined' | '/x-path' | new AlreadyDefinedException('', '')       || HttpStatus.CONFLICT
169     }
170
171     @Unroll
172     def 'Update data node leaves: #scenario.'() {
173         given: 'json data'
174             def jsonData = 'json data'
175             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
176         when: 'patch request is performed'
177             def response =
178                     mvc.perform(
179                             patch(endpoint)
180                                     .contentType(MediaType.APPLICATION_JSON)
181                                     .content(jsonData)
182                                     .param('xpath', xpath)
183                     ).andReturn().response
184         then: 'the service method is invoked with expected parameters'
185             1 * mockCpsDataService.updateNodeLeaves(dataspaceName, anchorName, xpathServiceParameter, jsonData)
186         and: 'response status indicates success'
187             response.status == HttpStatus.OK.value()
188         where:
189             scenario               | xpath    | xpathServiceParameter
190             'root node by default' | ''       | '/'
191             'node by parent xpath' | '/xpath' | '/xpath'
192     }
193
194     @Unroll
195     def 'Replace data node tree: #scenario.'() {
196         given: 'json data'
197             def jsonData = 'json data'
198             def endpoint = "$dataNodeBaseEndpoint/anchors/$anchorName/nodes"
199         when: 'put request is performed'
200             def response =
201                     mvc.perform(
202                             put(endpoint)
203                                     .contentType(MediaType.APPLICATION_JSON)
204                                     .content(jsonData)
205                                     .param('xpath', xpath))
206                             .andReturn().response
207         then: 'the service method is invoked with expected parameters'
208             1 * mockCpsDataService.replaceNodeTree(dataspaceName, anchorName, xpathServiceParameter, jsonData)
209         and: 'response status indicates success'
210             response.status == HttpStatus.OK.value()
211         where:
212             scenario               | xpath    | xpathServiceParameter
213             'root node by default' | ''       | '/'
214             'node by parent xpath' | '/xpath' | '/xpath'
215     }
216 }