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.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
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
56 class CpsRestExceptionHandlerSpec extends RestControllerSpecification {
59 CpsAdminService mockCpsAdminService = Mock()
62 CpsModuleService mockCpsModuleService = Mock()
65 CpsDataService mockCpsDataService = Mock()
68 CpsQueryService mockCpsQueryService = Mock()
71 ModelMapper modelMapper = Mock()
76 @Value('${rest.api.cps-base-path}')
80 def errorMessage = 'some error message'
82 def errorDetails = 'some error details'
84 def dataspaceName = 'MyDataSpace'
86 def existingObjectName = 'MyAdminObject'
89 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
91 when: 'runtime exception is thrown by the service'
92 setupTestException(new IllegalStateException(errorMessage))
93 def response = performTestRequest()
95 then: 'an HTTP Internal Server Error response is returned with correct message and details'
96 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
99 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
101 when: 'generic CPS exception is thrown by the service'
102 setupTestException(new CpsException(errorMessage, errorDetails))
103 def response = performTestRequest()
105 then: 'an HTTP Internal Server Error response is returned with correct message and details'
106 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
109 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
111 when: 'no data found CPS exception is thrown by the service'
112 def dataspaceName = 'MyDataSpace'
113 def descriptionOfObject = 'Description'
114 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
115 def response = performTestRequest()
117 then: 'an HTTP Not Found response is returned with correct message and details'
118 assertTestResponse(response, NOT_FOUND, 'Object not found',
119 'Description does not exist in dataspace MyDataSpace.')
123 def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
125 when: 'no data found CPS exception is thrown by the service'
126 setupTestException(exceptionThrown)
127 def response = performTestRequest()
129 then: 'an HTTP Bad Request response is returned with correct message an details'
130 assertTestResponse(response, BAD_REQUEST,
131 "Duplicate ${expectedObjectTypeInMessage}",
132 "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
133 'already exists for dataspace MyDataSpace.')
134 where: 'the following exceptions are thrown'
135 exceptionThrown || expectedObjectTypeInMessage
136 new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
137 new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Anchor'
141 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
143 when: 'CPS validation exception is thrown by the service'
144 setupTestException(exceptionThrown)
145 def response = performTestRequest()
147 then: 'an HTTP Bad Request response is returned with correct message and details'
148 assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
150 where: 'the following exceptions are thrown'
151 exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
152 new DataValidationException(errorMessage, errorDetails, null),
153 new CpsPathException(errorMessage,errorDetails)]
157 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
159 when: 'CPS validation exception is thrown by the service'
160 setupTestException(exceptionThrown)
161 def response = performTestRequest()
163 then: 'an HTTP Conflict response is returned with correct message and details'
164 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
166 where: 'the following exceptions are thrown'
167 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
168 new SchemaSetInUseException(dataspaceName, existingObjectName)]
171 def 'Get request without authentication is not authorized'() {
172 when: 'request is sent without authentication'
174 mvc.perform(get("$basePath/v1/dataspaces/dataspace-name/anchors")).andReturn().response
175 then: 'HTTP Unauthorized status code is returned'
176 assert UNAUTHORIZED.value() == response.status
179 def 'Get request with invalid authentication is not authorized'() {
180 when: 'request is sent with invalid authentication'
183 get("$basePath/v1/dataspaces/dataspace-name/anchors")
184 .header("Authorization", 'Basic invalid auth'))
185 .andReturn().response
186 then: 'HTTP Unauthorized status code is returned'
187 assert UNAUTHORIZED.value() == response.status
191 * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
192 * to test the exception handling. The endpoint chosen is not a subject of test.
195 def setupTestException(exception) {
196 mockCpsAdminService.getAnchors(_) >> { throw exception}
199 def performTestRequest() {
201 get("$basePath/v1/dataspaces/dataspace-name/anchors")
202 .header("Authorization", getAuthorizationHeader()))
203 .andReturn().response
206 void assertTestResponse(response, expectedStatus,
207 expectedErrorMessage, expectedErrorDetails) {
208 assert response.status == expectedStatus.value()
209 def content = new JsonSlurper().parseText(response.contentAsString)
210 assert content['status'] == expectedStatus.toString()
211 assert content['message'] == expectedErrorMessage
212 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails