General groovy test improvements
[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.post
27
28 import org.modelmapper.ModelMapper
29 import org.onap.cps.api.CpsAdminService
30 import org.onap.cps.api.CpsDataService
31 import org.onap.cps.api.CpsModuleService
32 import org.onap.cps.spi.exceptions.AnchorNotFoundException
33 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
34 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
35 import org.onap.cps.spi.model.DataNode
36 import org.onap.cps.spi.model.DataNodeBuilder
37 import org.spockframework.spring.SpringBean
38 import org.springframework.beans.factory.annotation.Autowired
39 import org.springframework.beans.factory.annotation.Value
40 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
41 import org.springframework.http.HttpStatus
42 import org.springframework.http.MediaType
43 import org.springframework.test.web.servlet.MockMvc
44 import spock.lang.Shared
45 import spock.lang.Specification
46 import spock.lang.Unroll
47
48 @WebMvcTest
49 class DataRestControllerSpec extends Specification {
50
51     @SpringBean
52     CpsDataService mockCpsDataService = Mock()
53
54     @SpringBean
55     CpsModuleService mockCpsModuleService = Mock()
56
57     @SpringBean
58     CpsAdminService mockCpsAdminService = Mock()
59
60     @SpringBean
61     ModelMapper modelMapper = Mock()
62
63     @Autowired
64     MockMvc mvc
65
66     @Value('${rest.api.cps-base-path}')
67     def basePath
68
69     def dataNodeEndpoint
70     def dataspaceName = 'my_dataspace'
71     def anchorName = 'my_anchor'
72
73     @Shared
74     static DataNode dataNodeWithLeavesNoChildren = new DataNodeBuilder().withXpath('/xpath')
75             .withLeaves([leaf:'value', leafList:['leaveListElement1','leaveListElement2']]).build()
76
77     @Shared
78     static DataNode dataNodeWithChild = new DataNodeBuilder().withXpath('/parent')
79             .withChildDataNodes([new DataNodeBuilder().withXpath("/parent/child").build()]).build()
80
81     def setup() {
82         dataNodeEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName/nodes"
83     }
84
85     def 'Create a node.'() {
86         given: 'some json to create a data node'
87             def json = 'some json (this is not validated)'
88         when: 'post is invoked with datanode endpoint and json'
89             def response = mvc.perform(
90                     post(dataNodeEndpoint).contentType(MediaType.APPLICATION_JSON).content(json)
91             ).andReturn().response
92         then: 'a created response is returned'
93             response.status == HttpStatus.CREATED.value()
94         then: 'the java API was called with the correct parameters'
95             1 * mockCpsDataService.saveData(dataspaceName, anchorName, json)
96     }
97
98     @Unroll
99     def 'Get data node with leaves'() {
100         given: 'the service returns data node leaves'
101             def xpath = 'some xPath'
102             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS) >> dataNodeWithLeavesNoChildren
103         when: 'get request is performed through REST API'
104             def response = mvc.perform(
105                     get(dataNodeEndpoint)
106                             .param('cps-path', xpath)
107             ).andReturn().response
108         then: 'a success response is returned'
109             response.status == HttpStatus.OK.value()
110         and: 'response contains expected leaf and value'
111             response.contentAsString.contains('"leaf":"value"')
112         and: 'response contains expected leaf-list and values'
113             response.contentAsString.contains('"leafList":["leaveListElement1","leaveListElement2"]')
114     }
115
116     @Unroll
117     def 'Get data node with #scenario.'() {
118         given: 'the service returns data node with #scenario'
119             def xpath = 'some xPath'
120             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, expectedCpsDataServiceOption) >> dataNode
121         when: 'get request is performed through REST API'
122             def response = mvc.perform(get(dataNodeEndpoint)
123                             .param('cps-path', xpath)
124                             .param('include-descendants', urlOption))
125                             .andReturn().response
126         then: 'a success response is returned'
127             response.status == HttpStatus.OK.value()
128         and: 'the response contains child is #expectChildInResponse'
129             response.contentAsString.contains('"child"') == expectChildInResponse
130         where:
131             scenario                    | dataNode                     | urlOption || expectedCpsDataServiceOption | expectChildInResponse
132             'no descendants by default' | dataNodeWithLeavesNoChildren | ''        || OMIT_DESCENDANTS             | false
133             'no descendant explicitly'  | dataNodeWithLeavesNoChildren | 'false'   || OMIT_DESCENDANTS             | false
134             'with descendants'          | dataNodeWithChild            | 'true'    || INCLUDE_ALL_DESCENDANTS      | true
135     }
136
137     @Unroll
138     def 'Get data node error scenario: #scenario.'() {
139         given: 'the service throws an exception'
140             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, _) >> { throw exception }
141         when: 'get request is performed through REST API'
142             def response = mvc.perform(
143                     get(dataNodeEndpoint).param("cps-path", xpath)
144             ).andReturn().response
145         then: 'a success response is returned'
146             response.status == httpStatus.value()
147         where:
148             scenario       | xpath     | exception                                 || httpStatus
149             'no dataspace' | '/x-path' | new DataspaceNotFoundException('')        || HttpStatus.BAD_REQUEST
150             'no anchor'    | '/x-path' | new AnchorNotFoundException('', '')       || HttpStatus.BAD_REQUEST
151             'no data'      | '/x-path' | new DataNodeNotFoundException('', '', '') || HttpStatus.NOT_FOUND
152             'empty path'   | ''        | new IllegalStateException()               || HttpStatus.NOT_IMPLEMENTED
153     }
154 }