Introducing Antlr4 for cpsPath parsing
[cps.git] / cps-rest / src / test / groovy / org / onap / cps / rest / exceptions / CpsRestExceptionHandlerSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Pantheon.tech
4  *  Copyright (C) 2021 Nordix Foundation
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.exceptions
23
24 import groovy.json.JsonSlurper
25 import org.modelmapper.ModelMapper
26 import org.onap.cps.api.CpsAdminService
27 import org.onap.cps.api.CpsDataService
28 import org.onap.cps.api.CpsModuleService
29 import org.onap.cps.api.CpsQueryService
30 import org.onap.cps.spi.exceptions.AlreadyDefinedException
31 import org.onap.cps.spi.exceptions.CpsException
32 import org.onap.cps.spi.exceptions.CpsPathException
33 import org.onap.cps.spi.exceptions.DataInUseException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataValidationException
36 import org.onap.cps.spi.exceptions.ModelValidationException
37 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
38 import org.onap.cps.spi.exceptions.SchemaSetInUseException
39 import org.spockframework.spring.SpringBean
40 import org.springframework.beans.factory.annotation.Autowired
41 import org.springframework.beans.factory.annotation.Value
42 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
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
48 import static org.springframework.http.HttpStatus.BAD_REQUEST
49 import static org.springframework.http.HttpStatus.CONFLICT
50 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
51 import static org.springframework.http.HttpStatus.NOT_FOUND
52 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
53 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
54
55 @WebMvcTest
56 class CpsRestExceptionHandlerSpec extends Specification {
57
58     @SpringBean
59     CpsAdminService mockCpsAdminService = Mock()
60
61     @SpringBean
62     CpsModuleService mockCpsModuleService = Mock()
63
64     @SpringBean
65     CpsDataService mockCpsDataService = Mock()
66
67     @SpringBean
68     CpsQueryService mockCpsQueryService = Mock()
69
70     @SpringBean
71     ModelMapper modelMapper = Mock()
72
73     @Autowired
74     MockMvc mvc
75
76     @Value('${rest.api.cps-base-path}')
77     def basePath
78
79     @Shared
80     def errorMessage = 'some error message'
81     @Shared
82     def errorDetails = 'some error details'
83     @Shared
84     def dataspaceName = 'MyDataSpace'
85     @Shared
86     def existingObjectName = 'MyAdminObject'
87
88
89     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
90         when: 'runtime exception is thrown by the service'
91             setupTestException(new IllegalStateException(errorMessage))
92             def response = performTestRequest()
93         then: 'an HTTP Internal Server Error response is returned with correct message and details'
94             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
95     }
96
97     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
98         when: 'generic CPS exception is thrown by the service'
99             setupTestException(new CpsException(errorMessage, errorDetails))
100             def response = performTestRequest()
101         then: 'an HTTP Internal Server Error response is returned with correct message and details'
102             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
103     }
104
105     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
106         when: 'no data found CPS exception is thrown by the service'
107             def dataspaceName = 'MyDataSpace'
108             def descriptionOfObject = 'Description'
109             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
110             def response = performTestRequest()
111         then: 'an HTTP Not Found response is returned with correct message and details'
112             assertTestResponse(response, NOT_FOUND, 'Object not found',
113                     'Description does not exist in dataspace MyDataSpace.')
114     }
115
116     def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
117         when: 'AlreadyDefinedException exception is thrown by the service'
118             setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
119             def response = performTestRequest()
120         then: 'a HTTP conflict response is returned with correct message an details'
121             assertTestResponse(response, CONFLICT,
122                     "Already defined exception",
123                     "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
124     }
125
126     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
127         when: 'CPS validation exception is thrown by the service'
128             setupTestException(exceptionThrown)
129             def response = performTestRequest()
130         then: 'an HTTP Bad Request response is returned with correct message and details'
131             assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
132         where: 'the following exceptions are thrown'
133             exceptionThrown                                                || expectedErrorMessage           | expectedErrorDetails
134             new ModelValidationException(errorMessage, errorDetails, null) || errorMessage                   | errorDetails
135             new DataValidationException(errorMessage, errorDetails, null)  || errorMessage                   | errorDetails
136             new CpsPathException(errorDetails)                             || CpsPathException.ERROR_MESSAGE | errorDetails
137     }
138
139     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
140         when: 'CPS validation exception is thrown by the service'
141             setupTestException(exceptionThrown)
142             def response = performTestRequest()
143         then: 'an HTTP Conflict response is returned with correct message and details'
144             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
145         where: 'the following exceptions are thrown'
146             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
147                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
148     }
149
150     /*
151      * NB. This method tests the expected behavior for POST request only;
152      * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
153      */
154     def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
155         given: '#exception is thrown the service indicating data is not found'
156             mockCpsDataService.saveData(_, _, _, _) >> { throw exceptionThrown }
157         when: 'data update request is performed'
158             def response = mvc.perform(
159                     post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
160                             .contentType(MediaType.APPLICATION_JSON)
161                             .param('xpath', 'parent node xpath')
162                             .content('json data')
163             ).andReturn().response
164         then: 'response code indicates bad input parameters'
165             response.status == BAD_REQUEST.value()
166         where: 'the following exceptions are thrown'
167             exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
168     }
169
170     /*
171      * NB. The test uses 'get anchors' endpoint and associated service method invocation
172      * to test the exception handling. The endpoint chosen is not a subject of test.
173      */
174
175     def setupTestException(exception) {
176         mockCpsAdminService.getAnchors(_) >> { throw exception }
177     }
178
179     def performTestRequest() {
180         return mvc.perform(
181                 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
182                 .andReturn().response
183     }
184
185     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
186         assert response.status == expectedStatus.value()
187         def content = new JsonSlurper().parseText(response.contentAsString)
188         assert content['status'] == expectedStatus.toString()
189         assert content['message'] == expectedErrorMessage
190         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
191     }
192 }