2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Pantheon.tech
4 * Modifications Copyright (C) 2021-2023 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.CpsDataspaceService
30 import org.onap.cps.api.CpsAnchorService
31 import org.onap.cps.api.CpsDataService
32 import org.onap.cps.api.CpsModuleService
33 import org.onap.cps.api.CpsQueryService
34 import org.onap.cps.rest.controller.CpsRestInputMapper
35 import org.onap.cps.spi.exceptions.AlreadyDefinedException
36 import org.onap.cps.spi.exceptions.CpsException
37 import org.onap.cps.spi.exceptions.CpsPathException
38 import org.onap.cps.spi.exceptions.DataInUseException
39 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
40 import org.onap.cps.spi.exceptions.DataValidationException
41 import org.onap.cps.spi.exceptions.ModelValidationException
42 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
43 import org.onap.cps.spi.exceptions.SchemaSetInUseException
44 import org.onap.cps.spi.exceptions.DataspaceInUseException
45 import org.onap.cps.utils.JsonObjectMapper
46 import org.onap.cps.utils.PrefixResolver
47 import org.spockframework.spring.SpringBean
48 import org.springframework.beans.factory.annotation.Autowired
49 import org.springframework.beans.factory.annotation.Value
50 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
51 import org.springframework.http.MediaType
52 import org.springframework.test.web.servlet.MockMvc
53 import spock.lang.Shared
54 import spock.lang.Specification
56 import static org.springframework.http.HttpStatus.BAD_REQUEST
57 import static org.springframework.http.HttpStatus.CONFLICT
58 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
59 import static org.springframework.http.HttpStatus.NOT_FOUND
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
61 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
64 class CpsRestExceptionHandlerSpec extends Specification {
67 CpsDataspaceService mockCpsAdminService = Stub()
70 CpsAnchorService mockCpsAnchorService = Stub()
73 CpsModuleService mockCpsModuleService = Stub()
76 CpsDataService mockCpsDataService = Stub()
79 CpsQueryService mockCpsQueryService = Stub()
82 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
85 CpsRestInputMapper cpsRestInputMapper = Stub()
88 PrefixResolver prefixResolver = Mock()
93 @Value('${rest.api.cps-base-path}')
97 def errorMessage = 'some error message'
99 def errorDetails = 'some error details'
101 def dataspaceName = 'MyDataSpace'
103 def existingObjectName = 'MyAdminObject'
106 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
107 when: 'runtime exception is thrown by the service'
108 setupTestException(new IllegalStateException(errorMessage))
109 def response = performTestRequest()
110 then: 'an HTTP Internal Server Error response is returned with correct message and details'
111 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
114 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
115 when: 'generic CPS exception is thrown by the service'
116 setupTestException(new CpsException(errorMessage, errorDetails))
117 def response = performTestRequest()
118 then: 'an HTTP Internal Server Error response is returned with correct message and details'
119 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
122 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
123 when: 'no data found CPS exception is thrown by the service'
124 def dataspaceName = 'MyDataSpace'
125 def descriptionOfObject = 'Description'
126 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
127 def response = performTestRequest()
128 then: 'an HTTP Not Found response is returned with correct message and details'
129 assertTestResponse(response, NOT_FOUND, 'Object not found',
130 'Description does not exist in dataspace MyDataSpace.')
133 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
134 when: 'AlreadyDefinedException exception is thrown by the service'
135 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
136 def response = performTestRequest()
137 then: 'a HTTP conflict response is returned with correct message an details'
138 assertTestResponse(response, CONFLICT,
139 "Already defined exception",
140 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
143 def 'Request with a schema set in use exception returns HTTP Status Conflict.'() {
144 when: 'Schema set in use exception is thrown by the service'
145 setupTestException(new SchemaSetInUseException(dataspaceName, existingObjectName))
146 def response = performTestRequest()
147 then: 'a HTTP conflict response is returned with correct message an details'
148 assertTestResponse(response, CONFLICT,
149 "Schema Set is being used.",
150 "Schema Set with name ${existingObjectName} in dataspace ${dataspaceName} is having Anchor records associated.")
153 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
154 when: '#exceptionThrown.class.simpleName is thrown by the service'
155 setupTestException(exceptionThrown)
156 def response = performTestRequest()
157 then: 'an HTTP Bad Request response is returned with correct message and details'
158 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
159 where: 'the following exceptions are thrown'
160 exceptionThrown || expectedErrorMessage | expectedErrorDetails
161 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
162 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
163 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
166 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
167 when: 'CPS validation exception is thrown by the service'
168 setupTestException(exceptionThrown)
169 def response = performTestRequest()
170 then: 'an HTTP Conflict response is returned with correct message and details'
171 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
172 where: 'the following exceptions are thrown'
173 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
174 new SchemaSetInUseException(dataspaceName, existingObjectName),
175 new DataspaceInUseException(dataspaceName, errorDetails)]
179 * NB. This method tests the expected behavior for POST request only;
180 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
183 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
184 given: '#exception is thrown the service indicating data is not found'
185 mockCpsDataService.saveData(*_) >> { throw exceptionThrown }
186 when: 'data update request is performed'
187 def response = mvc.perform(
188 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
189 .contentType(MediaType.APPLICATION_JSON)
190 .param('xpath', 'parent node xpath')
191 .content('{"some-key" : "some-value"}')
192 ).andReturn().response
193 then: 'response code indicates bad input parameters'
194 response.status == BAD_REQUEST.value()
195 where: 'the following exceptions are thrown'
196 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
200 * NB. The test uses 'get anchors' endpoint and associated service method invocation
201 * to test the exception handling. The endpoint chosen is not a subject of test.
204 def setupTestException(exception) {
205 mockCpsAnchorService.getAnchors(_) >> { throw exception }
208 def performTestRequest() {
210 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
211 .andReturn().response
214 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
215 assert response.status == expectedStatus.value()
216 def content = new JsonSlurper().parseText(response.contentAsString)
217 assert content['status'] == expectedStatus.toString()
218 assert content['message'] == expectedErrorMessage
219 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails