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