Improve error reporting for invalid cps path query
[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  *  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  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.rest.exceptions
23
24 import groovy.json.JsonSlurper
25 import org.modelmapper.ModelMapper
26 import org.onap.cps.api.CpsAdminService
27 import org.onap.cps.api.CpsDataService
28 import org.onap.cps.api.CpsModuleService
29 import org.onap.cps.api.CpsQueryService
30 import org.onap.cps.rest.controller.RestControllerSpecification
31 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
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.DataValidationException
36 import org.onap.cps.spi.exceptions.ModelValidationException
37 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
38 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
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.test.web.servlet.MockMvc
45 import spock.lang.Shared
46 import spock.lang.Unroll
47
48 import static org.springframework.http.HttpStatus.BAD_REQUEST
49 import static org.springframework.http.HttpStatus.CONFLICT
50 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
51 import static org.springframework.http.HttpStatus.NOT_FOUND
52 import static org.springframework.http.HttpStatus.UNAUTHORIZED
53 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
54
55 @WebMvcTest
56 class CpsRestExceptionHandlerSpec extends RestControllerSpecification {
57
58     @SpringBean
59     CpsAdminService mockCpsAdminService = Mock()
60
61     @SpringBean
62     CpsModuleService mockCpsModuleService = Mock()
63
64     @SpringBean
65     CpsDataService mockCpsDataService = Mock()
66
67     @SpringBean
68     CpsQueryService mockCpsQueryService = Mock()
69
70     @SpringBean
71     ModelMapper modelMapper = Mock()
72
73     @Autowired
74     MockMvc mvc
75
76     @Value('${rest.api.cps-base-path}')
77     def basePath
78
79     @Shared
80     def errorMessage = 'some error message'
81     @Shared
82     def errorDetails = 'some error details'
83     @Shared
84     def dataspaceName = 'MyDataSpace'
85     @Shared
86     def existingObjectName = 'MyAdminObject'
87
88
89     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
90
91         when: 'runtime exception is thrown by the service'
92             setupTestException(new IllegalStateException(errorMessage))
93             def response = performTestRequest()
94
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
101         when: 'generic CPS exception is thrown by the service'
102             setupTestException(new CpsException(errorMessage, errorDetails))
103             def response = performTestRequest()
104
105         then: 'an HTTP Internal Server Error response is returned with correct message and details'
106             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
107     }
108
109     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
110
111         when: 'no data found CPS exception is thrown by the service'
112             def dataspaceName = 'MyDataSpace'
113             def descriptionOfObject = 'Description'
114             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
115             def response = performTestRequest()
116
117         then: 'an HTTP Not Found response is returned with correct message and details'
118             assertTestResponse(response, NOT_FOUND, 'Object not found',
119                     'Description does not exist in dataspace MyDataSpace.')
120     }
121
122     @Unroll
123     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
124
125         when: 'no data found CPS exception is thrown by the service'
126             setupTestException(exceptionThrown)
127             def response = performTestRequest()
128
129         then: 'an HTTP Bad Request response is returned with correct message an details'
130             assertTestResponse(response, BAD_REQUEST,
131                     "Duplicate ${expectedObjectTypeInMessage}",
132                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
133                             'already exists for dataspace MyDataSpace.')
134         where: 'the following exceptions are thrown'
135             exceptionThrown                                                               || expectedObjectTypeInMessage
136             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
137             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
138     }
139
140     @Unroll
141     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
142
143         when: 'CPS validation exception is thrown by the service'
144             setupTestException(exceptionThrown)
145             def response = performTestRequest()
146
147         then: 'an HTTP Bad Request response is returned with correct message and details'
148             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
149
150         where: 'the following exceptions are thrown'
151             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
152                                 new DataValidationException(errorMessage, errorDetails, null),
153                                 new CpsPathException(errorMessage,errorDetails)]
154     }
155
156     @Unroll
157     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
158
159         when: 'CPS validation exception is thrown by the service'
160             setupTestException(exceptionThrown)
161             def response = performTestRequest()
162
163         then: 'an HTTP Conflict response is returned with correct message and details'
164             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
165
166         where: 'the following exceptions are thrown'
167             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
168                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
169     }
170
171     def 'Get request without authentication is not authorized'() {
172         when: 'request is sent without authentication'
173             def response =
174                     mvc.perform(get("$basePath/v1/dataspaces/dataspace-name/anchors")).andReturn().response
175         then: 'HTTP Unauthorized status code is returned'
176             assert UNAUTHORIZED.value() == response.status
177     }
178
179     def 'Get request with invalid authentication is not authorized'() {
180         when: 'request is sent with invalid authentication'
181             def response =
182                     mvc.perform(
183                             get("$basePath/v1/dataspaces/dataspace-name/anchors")
184                                     .header("Authorization", 'Basic invalid auth'))
185                             .andReturn().response
186         then: 'HTTP Unauthorized status code is returned'
187             assert UNAUTHORIZED.value() == response.status
188     }
189
190     /*
191      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
192      * to test the exception handling. The endpoint chosen is not a subject of test.
193      */
194
195     def setupTestException(exception) {
196         mockCpsAdminService.getAnchors(_) >> { throw exception}
197     }
198
199     def performTestRequest() {
200         return mvc.perform(
201                 get("$basePath/v1/dataspaces/dataspace-name/anchors")
202                         .header("Authorization", getAuthorizationHeader()))
203                 .andReturn().response
204     }
205
206     void assertTestResponse(response, expectedStatus,
207                             expectedErrorMessage, expectedErrorDetails) {
208         assert response.status == expectedStatus.value()
209         def content = new JsonSlurper().parseText(response.contentAsString)
210         assert content['status'] == expectedStatus.toString()
211         assert content['message'] == expectedErrorMessage
212         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
213     }
214 }