HTTP error code 500 changed to 400 for invalid JSON payload
[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-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
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.rest.exceptions
25
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
53
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
60
61 @WebMvcTest
62 class CpsRestExceptionHandlerSpec extends Specification {
63
64     @SpringBean
65     CpsAdminService mockCpsAdminService = Stub()
66
67     @SpringBean
68     CpsModuleService mockCpsModuleService = Stub()
69
70     @SpringBean
71     CpsDataService mockCpsDataService = Stub()
72
73     @SpringBean
74     CpsQueryService mockCpsQueryService = Stub()
75
76     @SpringBean
77     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
78
79     @SpringBean
80     CpsRestInputMapper cpsRestInputMapper = Stub()
81
82     @SpringBean
83     PrefixResolver prefixResolver = Mock()
84
85     @Autowired
86     MockMvc mvc
87
88     @Value('${rest.api.cps-base-path}')
89     def basePath
90
91     @Shared
92     def errorMessage = 'some error message'
93     @Shared
94     def errorDetails = 'some error details'
95     @Shared
96     def dataspaceName = 'MyDataSpace'
97     @Shared
98     def existingObjectName = 'MyAdminObject'
99
100
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)
107     }
108
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)
115     }
116
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.')
126     }
127
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}.")
136     }
137
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
149     }
150
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)]
161     }
162
163     /*
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.
166      */
167
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('', '')]
182     }
183
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')
190                     .content('{')
191             ).andReturn().response
192         then: 'response code indicates bad input parameters'
193             response.status == BAD_REQUEST.value()
194     }
195
196     /*
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.
199      */
200
201     def setupTestException(exception) {
202         mockCpsAdminService.getAnchors(_) >> { throw exception }
203     }
204
205     def performTestRequest() {
206         return mvc.perform(
207             get("$basePath/v1/dataspaces/dataspace-name/anchors"))
208             .andReturn().response
209     }
210
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
217     }
218 }