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 * ================================================================================
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 com.fasterxml.jackson.databind.ObjectMapper
26 import groovy.json.JsonSlurper
27 import org.mapstruct.factory.Mappers
28 import org.onap.cps.api.CpsAdminService
29 import org.onap.cps.api.CpsDataService
30 import org.onap.cps.api.CpsModuleService
31 import org.onap.cps.api.CpsQueryService
32 import org.onap.cps.rest.controller.CpsRestInputMapper
33 import org.onap.cps.spi.exceptions.AlreadyDefinedException
34 import org.onap.cps.spi.exceptions.CpsException
35 import org.onap.cps.spi.exceptions.CpsPathException
36 import org.onap.cps.spi.exceptions.DataInUseException
37 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
38 import org.onap.cps.spi.exceptions.DataValidationException
39 import org.onap.cps.spi.exceptions.ModelValidationException
40 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
41 import org.onap.cps.spi.exceptions.SchemaSetInUseException
42 import org.onap.cps.spi.exceptions.DataspaceInUseException
43 import org.onap.cps.utils.JsonObjectMapper
44 import org.spockframework.spring.SpringBean
45 import org.springframework.beans.factory.annotation.Autowired
46 import org.springframework.beans.factory.annotation.Value
47 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
48 import org.springframework.http.MediaType
49 import org.springframework.test.web.servlet.MockMvc
50 import spock.lang.Shared
51 import spock.lang.Specification
53 import static org.springframework.http.HttpStatus.BAD_REQUEST
54 import static org.springframework.http.HttpStatus.CONFLICT
55 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
56 import static org.springframework.http.HttpStatus.NOT_FOUND
57 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
58 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
61 class CpsRestExceptionHandlerSpec extends Specification {
64 CpsAdminService mockCpsAdminService = Stub()
67 CpsModuleService mockCpsModuleService = Stub()
70 CpsDataService mockCpsDataService = Stub()
73 CpsQueryService mockCpsQueryService = Stub()
76 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
79 CpsRestInputMapper cpsRestInputMapper = Stub()
84 @Value('${rest.api.cps-base-path}')
88 def errorMessage = 'some error message'
90 def errorDetails = 'some error details'
92 def dataspaceName = 'MyDataSpace'
94 def existingObjectName = 'MyAdminObject'
97 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
98 when: 'runtime exception is thrown by the service'
99 setupTestException(new IllegalStateException(errorMessage))
100 def response = performTestRequest()
101 then: 'an HTTP Internal Server Error response is returned with correct message and details'
102 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
105 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
106 when: 'generic CPS exception is thrown by the service'
107 setupTestException(new CpsException(errorMessage, errorDetails))
108 def response = performTestRequest()
109 then: 'an HTTP Internal Server Error response is returned with correct message and details'
110 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
113 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
114 when: 'no data found CPS exception is thrown by the service'
115 def dataspaceName = 'MyDataSpace'
116 def descriptionOfObject = 'Description'
117 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
118 def response = performTestRequest()
119 then: 'an HTTP Not Found response is returned with correct message and details'
120 assertTestResponse(response, NOT_FOUND, 'Object not found',
121 'Description does not exist in dataspace MyDataSpace.')
124 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
125 when: 'AlreadyDefinedException exception is thrown by the service'
126 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
127 def response = performTestRequest()
128 then: 'a HTTP conflict response is returned with correct message an details'
129 assertTestResponse(response, CONFLICT,
130 "Already defined exception",
131 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
134 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
135 when: 'CPS validation exception is thrown by the service'
136 setupTestException(exceptionThrown)
137 def response = performTestRequest()
138 then: 'an HTTP Bad Request response is returned with correct message and details'
139 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
140 where: 'the following exceptions are thrown'
141 exceptionThrown || expectedErrorMessage | expectedErrorDetails
142 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
143 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
144 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
147 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
148 when: 'CPS validation exception is thrown by the service'
149 setupTestException(exceptionThrown)
150 def response = performTestRequest()
151 then: 'an HTTP Conflict response is returned with correct message and details'
152 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
153 where: 'the following exceptions are thrown'
154 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
155 new SchemaSetInUseException(dataspaceName, existingObjectName),
156 new DataspaceInUseException(dataspaceName, errorDetails)]
160 * NB. This method tests the expected behavior for POST request only;
161 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
164 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
165 given: '#exception is thrown the service indicating data is not found'
166 mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
167 when: 'data update request is performed'
168 def response = mvc.perform(
169 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
170 .contentType(MediaType.APPLICATION_JSON)
171 .param('xpath', 'parent node xpath')
172 .content(groovy.json.JsonOutput.toJson('{"some-key" : "some-value"}'))
173 ).andReturn().response
174 then: 'response code indicates bad input parameters'
175 response.status == BAD_REQUEST.value()
176 where: 'the following exceptions are thrown'
177 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
181 * NB. The test uses 'get anchors' endpoint and associated service method invocation
182 * to test the exception handling. The endpoint chosen is not a subject of test.
185 def setupTestException(exception) {
186 mockCpsAdminService.getAnchors(_) >> { throw exception }
189 def performTestRequest() {
191 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
192 .andReturn().response
195 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
196 assert response.status == expectedStatus.value()
197 def content = new JsonSlurper().parseText(response.contentAsString)
198 assert content['status'] == expectedStatus.toString()
199 assert content['message'] == expectedErrorMessage
200 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails