f5968442d797d371e2660d1524cf2a6a20627cbb
[cps.git] / cps-rest / src / test / groovy / org / onap / cps / rest / exceptions / CpsRestExceptionHandlerSpec.groovy
1 /*
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
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.rest.exceptions
24
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.onap.cps.spi.exceptions.DataspaceInUseException
41 import org.spockframework.spring.SpringBean
42 import org.springframework.beans.factory.annotation.Autowired
43 import org.springframework.beans.factory.annotation.Value
44 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
45 import org.springframework.http.MediaType
46 import org.springframework.test.web.servlet.MockMvc
47 import spock.lang.Shared
48 import spock.lang.Specification
49
50 import static org.springframework.http.HttpStatus.BAD_REQUEST
51 import static org.springframework.http.HttpStatus.CONFLICT
52 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
53 import static org.springframework.http.HttpStatus.NOT_FOUND
54 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
55 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
56
57 @WebMvcTest
58 class CpsRestExceptionHandlerSpec extends Specification {
59
60     @SpringBean
61     CpsAdminService mockCpsAdminService = Mock()
62
63     @SpringBean
64     CpsModuleService mockCpsModuleService = Mock()
65
66     @SpringBean
67     CpsDataService mockCpsDataService = Mock()
68
69     @SpringBean
70     CpsQueryService mockCpsQueryService = Mock()
71
72     @SpringBean
73     ModelMapper modelMapper = Mock()
74
75     @Autowired
76     MockMvc mvc
77
78     @Value('${rest.api.cps-base-path}')
79     def basePath
80
81     @Shared
82     def errorMessage = 'some error message'
83     @Shared
84     def errorDetails = 'some error details'
85     @Shared
86     def dataspaceName = 'MyDataSpace'
87     @Shared
88     def existingObjectName = 'MyAdminObject'
89
90
91     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
92         when: 'runtime exception is thrown by the service'
93             setupTestException(new IllegalStateException(errorMessage))
94             def response = performTestRequest()
95         then: 'an HTTP Internal Server Error response is returned with correct message and details'
96             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
97     }
98
99     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
100         when: 'generic CPS exception is thrown by the service'
101             setupTestException(new CpsException(errorMessage, errorDetails))
102             def response = performTestRequest()
103         then: 'an HTTP Internal Server Error response is returned with correct message and details'
104             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
105     }
106
107     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
108         when: 'no data found CPS exception is thrown by the service'
109             def dataspaceName = 'MyDataSpace'
110             def descriptionOfObject = 'Description'
111             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
112             def response = performTestRequest()
113         then: 'an HTTP Not Found response is returned with correct message and details'
114             assertTestResponse(response, NOT_FOUND, 'Object not found',
115                 'Description does not exist in dataspace MyDataSpace.')
116     }
117
118     def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
119         when: 'AlreadyDefinedException exception is thrown by the service'
120             setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
121             def response = performTestRequest()
122         then: 'a HTTP conflict response is returned with correct message an details'
123             assertTestResponse(response, CONFLICT,
124                 "Already defined exception",
125                 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
126     }
127
128     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
129         when: 'CPS validation exception is thrown by the service'
130             setupTestException(exceptionThrown)
131             def response = performTestRequest()
132         then: 'an HTTP Bad Request response is returned with correct message and details'
133             assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
134         where: 'the following exceptions are thrown'
135             exceptionThrown                                                || expectedErrorMessage           | expectedErrorDetails
136             new ModelValidationException(errorMessage, errorDetails, null) || errorMessage                   | errorDetails
137             new DataValidationException(errorMessage, errorDetails, null)  || errorMessage                   | errorDetails
138             new CpsPathException(errorDetails)                             || CpsPathException.ERROR_MESSAGE | errorDetails
139     }
140
141     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
142         when: 'CPS validation exception is thrown by the service'
143             setupTestException(exceptionThrown)
144             def response = performTestRequest()
145         then: 'an HTTP Conflict response is returned with correct message and details'
146             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
147         where: 'the following exceptions are thrown'
148             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
149                                 new SchemaSetInUseException(dataspaceName, existingObjectName),
150                                 new DataspaceInUseException(dataspaceName, errorDetails)]
151     }
152
153     /*
154      * NB. This method tests the expected behavior for POST request only;
155      * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
156      */
157
158     def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
159         given: '#exception is thrown the service indicating data is not found'
160             mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
161         when: 'data update request is performed'
162             def response = mvc.perform(
163                 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
164                     .contentType(MediaType.APPLICATION_JSON)
165                     .param('xpath', 'parent node xpath')
166                     .content('json data')
167             ).andReturn().response
168         then: 'response code indicates bad input parameters'
169             response.status == BAD_REQUEST.value()
170         where: 'the following exceptions are thrown'
171             exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
172     }
173
174     /*
175      * NB. The test uses 'get anchors' endpoint and associated service method invocation
176      * to test the exception handling. The endpoint chosen is not a subject of test.
177      */
178
179     def setupTestException(exception) {
180         mockCpsAdminService.getAnchors(_) >> { throw exception }
181     }
182
183     def performTestRequest() {
184         return mvc.perform(
185             get("$basePath/v1/dataspaces/dataspace-name/anchors"))
186             .andReturn().response
187     }
188
189     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
190         assert response.status == expectedStatus.value()
191         def content = new JsonSlurper().parseText(response.contentAsString)
192         assert content['status'] == expectedStatus.toString()
193         assert content['message'] == expectedErrorMessage
194         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
195     }
196 }