2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Pantheon.tech
4 * Modifications 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
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.rest.exceptions
25 import groovy.json.JsonSlurper
26 import org.modelmapper.ModelMapper
27 import org.onap.cps.api.CpsAdminService
28 import org.onap.cps.api.CpsDataService
29 import org.onap.cps.api.CpsModuleService
30 import org.onap.cps.api.CpsQueryService
31 import org.onap.cps.spi.exceptions.AlreadyDefinedException
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.DataNodeNotFoundException
36 import org.onap.cps.spi.exceptions.DataValidationException
37 import org.onap.cps.spi.exceptions.ModelValidationException
38 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
39 import org.onap.cps.spi.exceptions.SchemaSetInUseException
40 import org.onap.cps.spi.exceptions.DataspaceInUseException
41 import org.spockframework.spring.SpringBean
42 import org.springframework.beans.factory.annotation.Autowired
43 import org.springframework.beans.factory.annotation.Value
44 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
45 import org.springframework.http.MediaType
46 import org.springframework.test.web.servlet.MockMvc
47 import spock.lang.Shared
48 import spock.lang.Specification
50 import static org.springframework.http.HttpStatus.BAD_REQUEST
51 import static org.springframework.http.HttpStatus.CONFLICT
52 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
53 import static org.springframework.http.HttpStatus.NOT_FOUND
54 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
55 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
58 class CpsRestExceptionHandlerSpec extends Specification {
61 CpsAdminService mockCpsAdminService = Mock()
64 CpsModuleService mockCpsModuleService = Mock()
67 CpsDataService mockCpsDataService = Mock()
70 CpsQueryService mockCpsQueryService = Mock()
73 ModelMapper modelMapper = Mock()
78 @Value('${rest.api.cps-base-path}')
82 def errorMessage = 'some error message'
84 def errorDetails = 'some error details'
86 def dataspaceName = 'MyDataSpace'
88 def existingObjectName = 'MyAdminObject'
91 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
92 when: 'runtime exception is thrown by the service'
93 setupTestException(new IllegalStateException(errorMessage))
94 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'() {
100 when: 'generic CPS exception is thrown by the service'
101 setupTestException(new CpsException(errorMessage, errorDetails))
102 def response = performTestRequest()
103 then: 'an HTTP Internal Server Error response is returned with correct message and details'
104 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
107 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
108 when: 'no data found CPS exception is thrown by the service'
109 def dataspaceName = 'MyDataSpace'
110 def descriptionOfObject = 'Description'
111 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
112 def response = performTestRequest()
113 then: 'an HTTP Not Found response is returned with correct message and details'
114 assertTestResponse(response, NOT_FOUND, 'Object not found',
115 'Description does not exist in dataspace MyDataSpace.')
118 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
119 when: 'AlreadyDefinedException exception is thrown by the service'
120 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
121 def response = performTestRequest()
122 then: 'a HTTP conflict response is returned with correct message an details'
123 assertTestResponse(response, CONFLICT,
124 "Already defined exception",
125 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
128 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
129 when: 'CPS validation exception is thrown by the service'
130 setupTestException(exceptionThrown)
131 def response = performTestRequest()
132 then: 'an HTTP Bad Request response is returned with correct message and details'
133 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
134 where: 'the following exceptions are thrown'
135 exceptionThrown || expectedErrorMessage | expectedErrorDetails
136 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
137 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
138 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
141 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
142 when: 'CPS validation exception is thrown by the service'
143 setupTestException(exceptionThrown)
144 def response = performTestRequest()
145 then: 'an HTTP Conflict response is returned with correct message and details'
146 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
147 where: 'the following exceptions are thrown'
148 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
149 new SchemaSetInUseException(dataspaceName, existingObjectName),
150 new DataspaceInUseException(dataspaceName, errorDetails)]
154 * NB. This method tests the expected behavior for POST request only;
155 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
158 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
159 given: '#exception is thrown the service indicating data is not found'
160 mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
161 when: 'data update request is performed'
162 def response = mvc.perform(
163 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
164 .contentType(MediaType.APPLICATION_JSON)
165 .param('xpath', 'parent node xpath')
166 .content(groovy.json.JsonOutput.toJson('{"some-key" : "some-value"}'))
167 ).andReturn().response
168 then: 'response code indicates bad input parameters'
169 response.status == BAD_REQUEST.value()
170 where: 'the following exceptions are thrown'
171 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
175 * NB. The test uses 'get anchors' endpoint and associated service method invocation
176 * to test the exception handling. The endpoint chosen is not a subject of test.
179 def setupTestException(exception) {
180 mockCpsAdminService.getAnchors(_) >> { throw exception }
183 def performTestRequest() {
185 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
186 .andReturn().response
189 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
190 assert response.status == expectedStatus.value()
191 def content = new JsonSlurper().parseText(response.contentAsString)
192 assert content['status'] == expectedStatus.toString()
193 assert content['message'] == expectedErrorMessage
194 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails