2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Pantheon.tech
4 * Modifications Copyright (C) 2021 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 groovy.json.JsonSlurper
26 import org.modelmapper.ModelMapper
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.spi.exceptions.AlreadyDefinedException
32 import org.onap.cps.spi.exceptions.CpsException
33 import org.onap.cps.spi.exceptions.CpsPathException
34 import org.onap.cps.spi.exceptions.DataInUseException
35 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
36 import org.onap.cps.spi.exceptions.DataValidationException
37 import org.onap.cps.spi.exceptions.ModelValidationException
38 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
39 import org.onap.cps.spi.exceptions.SchemaSetInUseException
40 import org.spockframework.spring.SpringBean
41 import org.springframework.beans.factory.annotation.Autowired
42 import org.springframework.beans.factory.annotation.Value
43 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
44 import org.springframework.http.MediaType
45 import org.springframework.test.web.servlet.MockMvc
46 import spock.lang.Shared
47 import spock.lang.Specification
49 import static org.springframework.http.HttpStatus.BAD_REQUEST
50 import static org.springframework.http.HttpStatus.CONFLICT
51 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
52 import static org.springframework.http.HttpStatus.NOT_FOUND
53 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
54 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
57 class CpsRestExceptionHandlerSpec extends Specification {
60 CpsAdminService mockCpsAdminService = Mock()
63 CpsModuleService mockCpsModuleService = Mock()
66 CpsDataService mockCpsDataService = Mock()
69 CpsQueryService mockCpsQueryService = Mock()
72 ModelMapper modelMapper = Mock()
77 @Value('${rest.api.cps-base-path}')
81 def errorMessage = 'some error message'
83 def errorDetails = 'some error details'
85 def dataspaceName = 'MyDataSpace'
87 def existingObjectName = 'MyAdminObject'
90 def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
91 when: 'runtime exception is thrown by the service'
92 setupTestException(new IllegalStateException(errorMessage))
93 def response = performTestRequest()
94 then: 'an HTTP Internal Server Error response is returned with correct message and details'
95 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
98 def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
99 when: 'generic CPS exception is thrown by the service'
100 setupTestException(new CpsException(errorMessage, errorDetails))
101 def response = performTestRequest()
102 then: 'an HTTP Internal Server Error response is returned with correct message and details'
103 assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
106 def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
107 when: 'no data found CPS exception is thrown by the service'
108 def dataspaceName = 'MyDataSpace'
109 def descriptionOfObject = 'Description'
110 setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
111 def response = performTestRequest()
112 then: 'an HTTP Not Found response is returned with correct message and details'
113 assertTestResponse(response, NOT_FOUND, 'Object not found',
114 'Description does not exist in dataspace MyDataSpace.')
117 def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
118 when: 'AlreadyDefinedException exception is thrown by the service'
119 setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
120 def response = performTestRequest()
121 then: 'a HTTP conflict response is returned with correct message an details'
122 assertTestResponse(response, CONFLICT,
123 "Already defined exception",
124 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
127 def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
128 when: 'CPS validation exception is thrown by the service'
129 setupTestException(exceptionThrown)
130 def response = performTestRequest()
131 then: 'an HTTP Bad Request response is returned with correct message and details'
132 assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
133 where: 'the following exceptions are thrown'
134 exceptionThrown || expectedErrorMessage | expectedErrorDetails
135 new ModelValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
136 new DataValidationException(errorMessage, errorDetails, null) || errorMessage | errorDetails
137 new CpsPathException(errorDetails) || CpsPathException.ERROR_MESSAGE | errorDetails
140 def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
141 when: 'CPS validation exception is thrown by the service'
142 setupTestException(exceptionThrown)
143 def response = performTestRequest()
144 then: 'an HTTP Conflict response is returned with correct message and details'
145 assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
146 where: 'the following exceptions are thrown'
147 exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
148 new SchemaSetInUseException(dataspaceName, existingObjectName)]
152 * NB. This method tests the expected behavior for POST request only;
153 * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
156 def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
157 given: '#exception is thrown the service indicating data is not found'
158 mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
159 when: 'data update request is performed'
160 def response = mvc.perform(
161 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
162 .contentType(MediaType.APPLICATION_JSON)
163 .param('xpath', 'parent node xpath')
164 .content('json data')
165 ).andReturn().response
166 then: 'response code indicates bad input parameters'
167 response.status == BAD_REQUEST.value()
168 where: 'the following exceptions are thrown'
169 exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
173 * NB. The test uses 'get anchors' endpoint and associated service method invocation
174 * to test the exception handling. The endpoint chosen is not a subject of test.
177 def setupTestException(exception) {
178 mockCpsAdminService.getAnchors(_) >> { throw exception }
181 def performTestRequest() {
183 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
184 .andReturn().response
187 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
188 assert response.status == expectedStatus.value()
189 def content = new JsonSlurper().parseText(response.contentAsString)
190 assert content['status'] == expectedStatus.toString()
191 assert content['message'] == expectedErrorMessage
192 assert expectedErrorDetails == null || content['details'] == expectedErrorDetails