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
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.rest.exceptions
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.DataInUseException
34 import org.onap.cps.spi.exceptions.DataValidationException
35 import org.onap.cps.spi.exceptions.ModelValidationException
36 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
37 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
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.test.web.servlet.MockMvc
44 import spock.lang.Shared
45 import spock.lang.Unroll
47 import static org.springframework.http.HttpStatus.BAD_REQUEST
48 import static org.springframework.http.HttpStatus.CONFLICT
49 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
50 import static org.springframework.http.HttpStatus.NOT_FOUND
51 import static org.springframework.http.HttpStatus.UNAUTHORIZED
52 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
55 class CpsRestExceptionHandlerSpec extends RestControllerSpecification {
58 CpsAdminService mockCpsAdminService = Mock()
61 CpsModuleService mockCpsModuleService = Mock()
64 CpsDataService mockCpsDataService = Mock()
67 CpsQueryService mockCpsQueryService = Mock()
70 ModelMapper modelMapper = Mock()
75 @Value('${rest.api.cps-base-path}')
79 def errorMessage = 'some error message'
81 def errorDetails = 'some error details'
83 def dataspaceName = 'MyDataSpace'
85 def existingObjectName = 'MyAdminObject'
88 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()
94 then: 'an HTTP Internal Server Error response is returned with correct message and details'
95 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
98 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
100 when: 'generic CPS exception is thrown by the service'
101 setupTestException(new CpsException(errorMessage, errorDetails))
102 def response = performTestRequest()
104 then: 'an HTTP Internal Server Error response is returned with correct message and details'
105 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
108 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
110 when: 'no data found CPS exception is thrown by the service'
111 def dataspaceName = 'MyDataSpace'
112 def descriptionOfObject = 'Description'
113 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
114 def response = performTestRequest()
116 then: 'an HTTP Not Found response is returned with correct message and details'
117 assertTestResponse(response, NOT_FOUND, 'Object not found',
118 'Description does not exist in dataspace MyDataSpace.')
122 def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
124 when: 'no data found CPS exception is thrown by the service'
125 setupTestException(exceptionThrown)
126 def response = performTestRequest()
128 then: 'an HTTP Bad Request response is returned with correct message an details'
129 assertTestResponse(response, BAD_REQUEST,
130 "Duplicate ${expectedObjectTypeInMessage}",
131 "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
132 'already exists for dataspace MyDataSpace.')
133 where: 'the following exceptions are thrown'
134 exceptionThrown || expectedObjectTypeInMessage
135 new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
136 new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Anchor'
140 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
142 when: 'CPS validation exception is thrown by the service'
143 setupTestException(exceptionThrown)
144 def response = performTestRequest()
146 then: 'an HTTP Bad Request response is returned with correct message and details'
147 assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
149 where: 'the following exceptions are thrown'
150 exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
151 new DataValidationException(errorMessage, errorDetails, null)]
155 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
157 when: 'CPS validation exception is thrown by the service'
158 setupTestException(exceptionThrown)
159 def response = performTestRequest()
161 then: 'an HTTP Conflict response is returned with correct message and details'
162 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
164 where: 'the following exceptions are thrown'
165 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
166 new SchemaSetInUseException(dataspaceName, existingObjectName)]
169 def 'Get request without authentication is not authorized'() {
170 when: 'request is sent without authentication'
172 mvc.perform(get("$basePath/v1/dataspaces/dataspace-name/anchors")).andReturn().response
173 then: 'HTTP Unauthorized status code is returned'
174 assert UNAUTHORIZED.value() == response.status
177 def 'Get request with invalid authentication is not authorized'() {
178 when: 'request is sent with invalid authentication'
181 get("$basePath/v1/dataspaces/dataspace-name/anchors")
182 .header("Authorization", 'Basic invalid auth'))
183 .andReturn().response
184 then: 'HTTP Unauthorized status code is returned'
185 assert UNAUTHORIZED.value() == response.status
189 * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
190 * to test the exception handling. The endpoint chosen is not a subject of test.
193 def setupTestException(exception) {
194 mockCpsAdminService.getAnchors(_) >> { throw exception}
197 def performTestRequest() {
199 get("$basePath/v1/dataspaces/dataspace-name/anchors")
200 .header("Authorization", getAuthorizationHeader()))
201 .andReturn().response
204 void assertTestResponse(response, expectedStatus,
205 expectedErrorMessage, expectedErrorDetails) {
206 assert response.status == expectedStatus.value()
207 def content = new JsonSlurper().parseText(response.contentAsString)
208 assert content['status'] == expectedStatus.toString()
209 assert content['message'] == expectedErrorMessage
210 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails