Exception stack trace is exposed
[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.rest.controller.RestControllerSpecification
31 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
32 import org.onap.cps.spi.exceptions.CpsException
33 import org.onap.cps.spi.exceptions.CpsPathException
34 import org.onap.cps.spi.exceptions.DataInUseException
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.SchemaSetAlreadyDefinedException
39 import org.onap.cps.spi.exceptions.SchemaSetInUseException
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.test.web.servlet.MockMvc
45 import spock.lang.Shared
46 import spock.lang.Unroll
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.http.HttpStatus.UNAUTHORIZED
53 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
54
55 @WebMvcTest
56 class CpsRestExceptionHandlerSpec extends RestControllerSpecification {
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     @Unroll
117     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
118         when: 'no data found CPS exception is thrown by the service'
119             setupTestException(exceptionThrown)
120             def response = performTestRequest()
121         then: 'an HTTP Bad Request response is returned with correct message an details'
122             assertTestResponse(response, BAD_REQUEST,
123                     "Duplicate ${expectedObjectTypeInMessage}",
124                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
125                             'already exists for dataspace MyDataSpace.')
126         where: 'the following exceptions are thrown'
127             exceptionThrown                                                               || expectedObjectTypeInMessage
128             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
129             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
130     }
131
132     @Unroll
133     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
134         when: 'CPS validation exception is thrown by the service'
135             setupTestException(exceptionThrown)
136             def response = performTestRequest()
137         then: 'an HTTP Bad Request response is returned with correct message and details'
138             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
139         where: 'the following exceptions are thrown'
140             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
141                                 new DataValidationException(errorMessage, errorDetails, null),
142                                 new CpsPathException(errorMessage,errorDetails)]
143     }
144
145     @Unroll
146     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
147         when: 'CPS validation exception is thrown by the service'
148             setupTestException(exceptionThrown)
149             def response = performTestRequest()
150         then: 'an HTTP Conflict response is returned with correct message and details'
151             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
152         where: 'the following exceptions are thrown'
153             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
154                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
155     }
156
157     def 'Get request without authentication is not authorized'() {
158         when: 'request is sent without authentication'
159             def response =
160                     mvc.perform(get("$basePath/v1/dataspaces/dataspace-name/anchors")).andReturn().response
161         then: 'HTTP Unauthorized status code is returned'
162             assert UNAUTHORIZED.value() == response.status
163     }
164
165     def 'Get request with invalid authentication is not authorized'() {
166         when: 'request is sent with invalid authentication'
167             def response =
168                     mvc.perform(
169                             get("$basePath/v1/dataspaces/dataspace-name/anchors")
170                                     .header("Authorization", 'Basic invalid auth'))
171                             .andReturn().response
172         then: 'HTTP Unauthorized status code is returned'
173             assert UNAUTHORIZED.value() == response.status
174     }
175
176     /*
177      * NB. The test uses 'get anchors' endpoint and associated service method invocation
178      * to test the exception handling. The endpoint chosen is not a subject of test.
179      */
180     def setupTestException(exception) {
181         mockCpsAdminService.getAnchors(_) >> { throw exception}
182     }
183
184     def performTestRequest() {
185         return mvc.perform(
186                 get("$basePath/v1/dataspaces/dataspace-name/anchors")
187                         .header("Authorization", getAuthorizationHeader()))
188                 .andReturn().response
189     }
190
191     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
192         assert response.status == expectedStatus.value()
193         def content = new JsonSlurper().parseText(response.contentAsString)
194         assert content['status'] == expectedStatus.toString()
195         assert content['message'] == expectedErrorMessage
196         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
197     }
198 }