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