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