Delete schema set - REST and service layers
[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  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.rest.exceptions
21
22 import groovy.json.JsonSlurper
23 import org.modelmapper.ModelMapper
24 import org.onap.cps.api.CpsAdminService
25 import org.onap.cps.api.CpsModuleService
26 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
27 import org.onap.cps.spi.exceptions.CpsException
28 import org.onap.cps.spi.exceptions.DataInUseException
29 import org.onap.cps.spi.exceptions.DataValidationException
30 import org.onap.cps.spi.exceptions.ModelValidationException
31 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
32 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
33 import org.onap.cps.spi.exceptions.SchemaSetInUseException
34 import org.spockframework.spring.SpringBean
35 import org.springframework.beans.factory.annotation.Autowired
36 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
37 import org.springframework.test.web.servlet.MockMvc
38 import spock.lang.Shared
39 import spock.lang.Specification
40 import spock.lang.Unroll
41
42 import static org.springframework.http.HttpStatus.BAD_REQUEST
43 import static org.springframework.http.HttpStatus.CONFLICT
44 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
45 import static org.springframework.http.HttpStatus.NOT_FOUND
46 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
47
48 @WebMvcTest
49 class CpsRestExceptionHandlerSpec extends Specification {
50
51     @SpringBean
52     CpsAdminService mockCpsAdminService = Mock()
53
54     @SpringBean
55     CpsModuleService mockCpsModuleService = Mock()
56
57     @SpringBean
58     ModelMapper modelMapper = Mock()
59
60     @Autowired
61     MockMvc mvc
62
63     @Shared
64     def errorMessage = 'some error message'
65     @Shared
66     def errorDetails = 'some error details'
67     @Shared
68     def dataspaceName = 'MyDataSpace'
69     @Shared
70     def existingObjectName = 'MyAdminObject'
71
72
73     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
74
75         when: 'runtime exception is thrown by the service'
76             setupTestException(new IllegalStateException(errorMessage))
77             def response = performTestRequest()
78
79         then: 'an HTTP Internal Server Error response is returned with correct message and details'
80             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
81     }
82
83     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
84
85         when: 'generic CPS exception is thrown by the service'
86             setupTestException(new CpsException(errorMessage, errorDetails))
87             def response = performTestRequest()
88
89         then: 'an HTTP Internal Server Error response is returned with correct message and details'
90             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
91     }
92
93     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
94
95         when: 'no data found CPS exception is thrown by the service'
96             def dataspaceName = 'MyDataSpace'
97             def descriptionOfObject = 'Description'
98             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
99             def response = performTestRequest()
100
101         then: 'an HTTP Not Found response is returned with correct message and details'
102             assertTestResponse(response, NOT_FOUND, 'Object not found',
103                     'Description does not exist in dataspace MyDataSpace.')
104     }
105
106     @Unroll
107     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
108
109         when: 'no data found CPS exception is thrown by the service'
110             setupTestException(exceptionThrown)
111             def response = performTestRequest()
112
113         then: 'an HTTP Bad Request response is returned with correct message an details'
114             assertTestResponse(response, BAD_REQUEST,
115                     "Duplicate ${expectedObjectTypeInMessage}",
116                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
117                             'already exists for dataspace MyDataSpace.')
118         where: 'the following exceptions are thrown'
119             exceptionThrown                                                               || expectedObjectTypeInMessage
120             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
121             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
122     }
123
124     @Unroll
125     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
126
127         when: 'CPS validation exception is thrown by the service'
128             setupTestException(exceptionThrown)
129             def response = performTestRequest()
130
131         then: 'an HTTP Bad Request response is returned with correct message and details'
132             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
133
134         where: 'the following exceptions are thrown'
135             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
136                                 new DataValidationException(errorMessage, errorDetails, null)]
137     }
138
139     @Unroll
140     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
141
142         when: 'CPS validation exception is thrown by the service'
143             setupTestException(exceptionThrown)
144             def response = performTestRequest()
145
146         then: 'an HTTP Conflict response is returned with correct message and details'
147             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
148
149         where: 'the following exceptions are thrown'
150             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
151                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
152     }
153
154     /*
155      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
156      * to test the exception handling. The endpoint chosen is not a subject of test.
157      */
158
159     def setupTestException(exception) {
160         mockCpsAdminService.getAnchors(_) >> { throw exception}
161     }
162
163     def performTestRequest() {
164         return mvc.perform(get('/v1/dataspaces/dataspace-name/anchors')).andReturn().response
165     }
166
167     void assertTestResponse(response, expectedStatus,
168                             expectedErrorMessage, expectedErrorDetails) {
169         assert response.status == expectedStatus.value()
170         def content = new JsonSlurper().parseText(response.contentAsString)
171         assert content['status'] == expectedStatus.toString()
172         assert content['message'] == expectedErrorMessage
173         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
174     }
175 }