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