Move web security configuration to application module
[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 static org.springframework.http.HttpStatus.BAD_REQUEST
25 import static org.springframework.http.HttpStatus.CONFLICT
26 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
27 import static org.springframework.http.HttpStatus.NOT_FOUND
28 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
29
30 import groovy.json.JsonSlurper
31 import org.modelmapper.ModelMapper
32 import org.onap.cps.api.CpsAdminService
33 import org.onap.cps.api.CpsDataService
34 import org.onap.cps.api.CpsModuleService
35 import org.onap.cps.api.CpsQueryService
36 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
37 import org.onap.cps.spi.exceptions.CpsException
38 import org.onap.cps.spi.exceptions.CpsPathException
39 import org.onap.cps.spi.exceptions.DataInUseException
40 import org.onap.cps.spi.exceptions.DataValidationException
41 import org.onap.cps.spi.exceptions.ModelValidationException
42 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
43 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
44 import org.onap.cps.spi.exceptions.SchemaSetInUseException
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.test.web.servlet.MockMvc
50 import spock.lang.Shared
51 import spock.lang.Specification
52 import spock.lang.Unroll
53
54 @WebMvcTest
55 class CpsRestExceptionHandlerSpec extends Specification {
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                                 new CpsPathException(errorMessage, errorDetails)]
153     }
154
155     @Unroll
156     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
157
158         when: 'CPS validation exception is thrown by the service'
159             setupTestException(exceptionThrown)
160             def response = performTestRequest()
161
162         then: 'an HTTP Conflict response is returned with correct message and details'
163             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
164
165         where: 'the following exceptions are thrown'
166             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
167                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
168     }
169
170     /*
171      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
172      * to test the exception handling. The endpoint chosen is not a subject of test.
173      */
174
175     def setupTestException(exception) {
176         mockCpsAdminService.getAnchors(_) >> { throw exception }
177     }
178
179     def performTestRequest() {
180         return mvc.perform(
181                 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
182                 .andReturn().response
183     }
184
185     void assertTestResponse(response, expectedStatus,
186                             expectedErrorMessage, expectedErrorDetails) {
187         assert response.status == expectedStatus.value()
188         def content = new JsonSlurper().parseText(response.contentAsString)
189         assert content['status'] == expectedStatus.toString()
190         assert content['message'] == expectedErrorMessage
191         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
192     }
193 }