2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Pantheon.tech
4 * Modifications Copyright (C) 2021-2022 Nordix Foundation
5 * Modifications Copyright (C) 2021 Bell Canada.
6 * Modifications Copyright (C) 2022 TechMahindra Ltd.
7 * Modifications Copyright (C) 2022 Deutsche Telekom AG
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * SPDX-License-Identifier: Apache-2.0
22 * ============LICENSE_END=========================================================
25 package org.onap.cps.rest.exceptions
27 import com.fasterxml.jackson.databind.ObjectMapper
28 import groovy.json.JsonSlurper
29 import org.onap.cps.api.CpsAdminService
30 import org.onap.cps.api.CpsDataService
31 import org.onap.cps.api.CpsModuleService
32 import org.onap.cps.api.CpsQueryService
33 import org.onap.cps.rest.controller.CpsRestInputMapper
34 import org.onap.cps.spi.exceptions.AlreadyDefinedException
35 import org.onap.cps.spi.exceptions.CpsException
36 import org.onap.cps.spi.exceptions.CpsPathException
37 import org.onap.cps.spi.exceptions.DataInUseException
38 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
39 import org.onap.cps.spi.exceptions.DataValidationException
40 import org.onap.cps.spi.exceptions.ModelValidationException
41 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
42 import org.onap.cps.spi.exceptions.SchemaSetInUseException
43 import org.onap.cps.spi.exceptions.DataspaceInUseException
44 import org.onap.cps.utils.JsonObjectMapper
45 import org.onap.cps.utils.PrefixResolver
46 import org.spockframework.spring.SpringBean
47 import org.springframework.beans.factory.annotation.Autowired
48 import org.springframework.beans.factory.annotation.Value
49 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
50 import org.springframework.http.MediaType
51 import org.springframework.test.web.servlet.MockMvc
52 import spock.lang.Shared
53 import spock.lang.Specification
55 import static org.springframework.http.HttpStatus.BAD_REQUEST
56 import static org.springframework.http.HttpStatus.CONFLICT
57 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
58 import static org.springframework.http.HttpStatus.NOT_FOUND
59 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
63 class CpsRestExceptionHandlerSpec extends Specification {
66 CpsAdminService mockCpsAdminService = Stub()
69 CpsModuleService mockCpsModuleService = Stub()
72 CpsDataService mockCpsDataService = Stub()
75 CpsQueryService mockCpsQueryService = Stub()
78 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
81 CpsRestInputMapper cpsRestInputMapper = Stub()
84 PrefixResolver prefixResolver = Mock()
89 @Value('${rest.api.cps-base-path}')
93 def errorMessage = 'some error message'
95 def errorDetails = 'some error details'
97 def dataspaceName = 'MyDataSpace'
99 def existingObjectName = 'MyAdminObject'
102 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
103 when: 'runtime exception is thrown by the service'
104 setupTestException(new IllegalStateException(errorMessage))
105 def response = performTestRequest()
106 then: 'an HTTP Internal Server Error response is returned with correct message and details'
107 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
110 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
111 when: 'generic CPS exception is thrown by the service'
112 setupTestException(new CpsException(errorMessage, errorDetails))
113 def response = performTestRequest()
114 then: 'an HTTP Internal Server Error response is returned with correct message and details'
115 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
118 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
119 when: 'no data found CPS exception is thrown by the service'
120 def dataspaceName = 'MyDataSpace'
121 def descriptionOfObject = 'Description'
122 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
123 def response = performTestRequest()
124 then: 'an HTTP Not Found response is returned with correct message and details'
125 assertTestResponse(response, NOT_FOUND, 'Object not found',
126 'Description does not exist in dataspace MyDataSpace.')
129 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
130 when: 'AlreadyDefinedException exception is thrown by the service'
131 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
132 def response = performTestRequest()
133 then: 'a HTTP conflict response is returned with correct message an details'
134 assertTestResponse(response, CONFLICT,
135 "Already defined exception",
136 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
139 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
140 when: 'CPS validation exception is thrown by the service'
141 setupTestException(exceptionThrown)
142 def response = performTestRequest()
143 then: 'an HTTP Bad Request response is returned with correct message and details'
144 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
145 where: 'the following exceptions are thrown'
146 exceptionThrown || expectedErrorMessage | expectedErrorDetails
147 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
148 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
149 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
152 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
153 when: 'CPS validation exception is thrown by the service'
154 setupTestException(exceptionThrown)
155 def response = performTestRequest()
156 then: 'an HTTP Conflict response is returned with correct message and details'
157 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
158 where: 'the following exceptions are thrown'
159 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
160 new SchemaSetInUseException(dataspaceName, existingObjectName),
161 new DataspaceInUseException(dataspaceName, errorDetails)]
165 * NB. This method tests the expected behavior for POST request only;
166 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
169 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
170 given: '#exception is thrown the service indicating data is not found'
171 mockCpsDataService.saveData(*_) >> { throw exceptionThrown }
172 when: 'data update request is performed'
173 def response = mvc.perform(
174 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
175 .contentType(MediaType.APPLICATION_JSON)
176 .param('xpath', 'parent node xpath')
177 .content('{"some-key" : "some-value"}')
178 ).andReturn().response
179 then: 'response code indicates bad input parameters'
180 response.status == BAD_REQUEST.value()
181 where: 'the following exceptions are thrown'
182 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
186 * NB. The test uses 'get anchors' endpoint and associated service method invocation
187 * to test the exception handling. The endpoint chosen is not a subject of test.
190 def setupTestException(exception) {
191 mockCpsAdminService.getAnchors(_) >> { throw exception }
194 def performTestRequest() {
196 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
197 .andReturn().response
200 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
201 assert response.status == expectedStatus.value()
202 def content = new JsonSlurper().parseText(response.contentAsString)
203 assert content['status'] == expectedStatus.toString()
204 assert content['message'] == expectedErrorMessage
205 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails