Fetching data node by xpath - rest and service layers
[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 com.google.common.collect.ImmutableMap
29 import org.modelmapper.ModelMapper
30 import org.onap.cps.api.CpsAdminService
31 import org.onap.cps.api.CpsDataService
32 import org.onap.cps.api.CpsModuleService
33 import org.onap.cps.spi.exceptions.AnchorNotFoundException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
36 import org.onap.cps.spi.model.DataNode
37 import org.onap.cps.spi.model.DataNodeBuilder
38 import org.spockframework.spring.SpringBean
39 import org.springframework.beans.factory.annotation.Autowired
40 import org.springframework.beans.factory.annotation.Value
41 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
42 import org.springframework.http.HttpStatus
43 import org.springframework.http.MediaType
44 import org.springframework.test.web.servlet.MockMvc
45 import spock.lang.Shared
46 import spock.lang.Specification
47 import spock.lang.Unroll
48
49 import javax.annotation.PostConstruct
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     ModelMapper modelMapper = Mock()
65
66     @Autowired
67     MockMvc mvc
68
69     @Value('${rest.api.cps-base-path}')
70     def basePath
71
72     String dataNodeEndpoint
73     def dataspaceName = 'my_dataspace'
74     def anchorName = 'my_anchor'
75
76     @Shared
77     static DataNode dataNodeNoChildren = new DataNodeBuilder().withXpath("/xpath")
78             .withLeaves(ImmutableMap.of("leaf", "value")).build()
79
80     @Shared
81     static DataNode dataNodeWithChild = new DataNodeBuilder().withXpath("/parent")
82             .withChildDataNodes(Arrays.asList(
83                     new DataNodeBuilder().withXpath("/parent/child").build()
84             )).build()
85
86     @PostConstruct
87     def initEndpoints() {
88         dataNodeEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName/nodes"
89     }
90
91     def 'Create a node.'() {
92         given: 'an endpoint'
93             def json = 'some json (this is not validated)'
94         when: 'post is invoked'
95             def response = mvc.perform(
96                     post(dataNodeEndpoint).contentType(MediaType.APPLICATION_JSON).content(json)
97             ).andReturn().response
98         then: 'the java API is called with the correct parameters'
99             1 * mockCpsDataService.saveData(dataspaceName, anchorName, json)
100             response.status == HttpStatus.CREATED.value()
101     }
102
103     @Unroll
104     def 'Get data node with #scenario.'() {
105         given: 'the service returns data node #scenario'
106             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, fetchDescendantsOption) >> dataNode
107         when: 'get request is performed through REST API'
108             def response = mvc.perform(
109                     get(dataNodeEndpoint)
110                             .param('cps-path', xpath)
111                             .param('include-descendants', includeDescendants)
112             ).andReturn().response
113         then: 'assert the success response returned'
114             response.status == HttpStatus.OK.value()
115         and: 'response contains expected value'
116             response.contentAsString.contains(checkString)
117         where:
118             scenario                    | dataNode           | xpath     | includeDescendants | fetchDescendantsOption  || checkString
119             'no descendants by default' | dataNodeNoChildren | '/xpath'  | ''                 | OMIT_DESCENDANTS        || '"leaf"'
120             'no descendant explicitly'  | dataNodeNoChildren | '/xpath'  | 'false'            | OMIT_DESCENDANTS        || '"leaf"'
121             'with descendants'          | dataNodeWithChild  | '/parent' | 'true'             | INCLUDE_ALL_DESCENDANTS || '"child"'
122     }
123
124     @Unroll
125     def 'Get data node error scenario: #scenario.'() {
126         given: 'the service returns throws an exception'
127             mockCpsDataService.getDataNode(dataspaceName, anchorName, xpath, _) >> { throw exception }
128         when: 'get request is performed through REST API'
129             def response = mvc.perform(
130                     get(dataNodeEndpoint).param("cps-path", xpath)
131             ).andReturn().response
132         then: 'assert the success response returned'
133             response.status == httpStatus.value()
134         where:
135             scenario       | xpath     | exception                                 || httpStatus
136             'no dataspace' | '/x-path' | new DataspaceNotFoundException('')        || HttpStatus.BAD_REQUEST
137             'no anchor'    | '/x-path' | new AnchorNotFoundException('', '')       || HttpStatus.BAD_REQUEST
138             'no data'      | '/x-path' | new DataNodeNotFoundException('', '', '') || HttpStatus.NOT_FOUND
139             'empty path'   | ''        | new IllegalStateException()               || HttpStatus.NOT_IMPLEMENTED
140     }
141 }