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 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.rest.exceptions
26 import com.fasterxml.jackson.databind.ObjectMapper
27 import groovy.json.JsonSlurper
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.onap.cps.utils.PrefixResolver
45 import org.spockframework.spring.SpringBean
46 import org.springframework.beans.factory.annotation.Autowired
47 import org.springframework.beans.factory.annotation.Value
48 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
49 import org.springframework.http.MediaType
50 import org.springframework.test.web.servlet.MockMvc
51 import spock.lang.Shared
52 import spock.lang.Specification
54 import static org.springframework.http.HttpStatus.BAD_REQUEST
55 import static org.springframework.http.HttpStatus.CONFLICT
56 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
57 import static org.springframework.http.HttpStatus.NOT_FOUND
58 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
59 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
62 class CpsRestExceptionHandlerSpec extends Specification {
65 CpsAdminService mockCpsAdminService = Stub()
68 CpsModuleService mockCpsModuleService = Stub()
71 CpsDataService mockCpsDataService = Stub()
74 CpsQueryService mockCpsQueryService = Stub()
77 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
80 CpsRestInputMapper cpsRestInputMapper = Stub()
83 PrefixResolver prefixResolver = Mock()
88 @Value('${rest.api.cps-base-path}')
92 def errorMessage = 'some error message'
94 def errorDetails = 'some error details'
96 def dataspaceName = 'MyDataSpace'
98 def existingObjectName = 'MyAdminObject'
101 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
102 when: 'runtime exception is thrown by the service'
103 setupTestException(new IllegalStateException(errorMessage))
104 def response = performTestRequest()
105 then: 'an HTTP Internal Server Error response is returned with correct message and details'
106 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
109 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
110 when: 'generic CPS exception is thrown by the service'
111 setupTestException(new CpsException(errorMessage, errorDetails))
112 def response = performTestRequest()
113 then: 'an HTTP Internal Server Error response is returned with correct message and details'
114 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
117 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
118 when: 'no data found CPS exception is thrown by the service'
119 def dataspaceName = 'MyDataSpace'
120 def descriptionOfObject = 'Description'
121 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
122 def response = performTestRequest()
123 then: 'an HTTP Not Found response is returned with correct message and details'
124 assertTestResponse(response, NOT_FOUND, 'Object not found',
125 'Description does not exist in dataspace MyDataSpace.')
128 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
129 when: 'AlreadyDefinedException exception is thrown by the service'
130 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
131 def response = performTestRequest()
132 then: 'a HTTP conflict response is returned with correct message an details'
133 assertTestResponse(response, CONFLICT,
134 "Already defined exception",
135 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
138 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
139 when: 'CPS validation exception is thrown by the service'
140 setupTestException(exceptionThrown)
141 def response = performTestRequest()
142 then: 'an HTTP Bad Request response is returned with correct message and details'
143 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
144 where: 'the following exceptions are thrown'
145 exceptionThrown || expectedErrorMessage | expectedErrorDetails
146 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
147 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
148 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
151 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
152 when: 'CPS validation exception is thrown by the service'
153 setupTestException(exceptionThrown)
154 def response = performTestRequest()
155 then: 'an HTTP Conflict response is returned with correct message and details'
156 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
157 where: 'the following exceptions are thrown'
158 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
159 new SchemaSetInUseException(dataspaceName, existingObjectName),
160 new DataspaceInUseException(dataspaceName, errorDetails)]
164 * NB. This method tests the expected behavior for POST request only;
165 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
168 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
169 given: '#exception is thrown the service indicating data is not found'
170 mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
171 when: 'data update request is performed'
172 def response = mvc.perform(
173 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
174 .contentType(MediaType.APPLICATION_JSON)
175 .param('xpath', 'parent node xpath')
176 .content(groovy.json.JsonOutput.toJson('{"some-key" : "some-value"}'))
177 ).andReturn().response
178 then: 'response code indicates bad input parameters'
179 response.status == BAD_REQUEST.value()
180 where: 'the following exceptions are thrown'
181 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
184 def 'Post request with invalid JSON payload returns HTTP Status Bad Request.'() {
185 when: 'data post request is performed'
186 def response = mvc.perform(
187 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
188 .contentType(MediaType.APPLICATION_JSON)
189 .param('xpath', 'parent node xpath')
191 ).andReturn().response
192 then: 'response code indicates bad input parameters'
193 response.status == BAD_REQUEST.value()
197 * NB. The test uses 'get anchors' endpoint and associated service method invocation
198 * to test the exception handling. The endpoint chosen is not a subject of test.
201 def setupTestException(exception) {
202 mockCpsAdminService.getAnchors(_) >> { throw exception }
205 def performTestRequest() {
207 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
208 .andReturn().response
211 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
212 assert response.status == expectedStatus.value()
213 def content = new JsonSlurper().parseText(response.contentAsString)
214 assert content['status'] == expectedStatus.toString()
215 assert content['message'] == expectedErrorMessage
216 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails