fb4037271bb80e56ac6b0829bba3461c265e324f
[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         when: 'runtime exception is thrown by the service'
90             setupTestException(new IllegalStateException(errorMessage))
91             def response = performTestRequest()
92         then: 'an HTTP Internal Server Error response is returned with correct message and details'
93             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
94     }
95
96     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
97         when: 'generic CPS exception is thrown by the service'
98             setupTestException(new CpsException(errorMessage, errorDetails))
99             def response = performTestRequest()
100         then: 'an HTTP Internal Server Error response is returned with correct message and details'
101             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
102     }
103
104     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
105         when: 'no data found CPS exception is thrown by the service'
106             def dataspaceName = 'MyDataSpace'
107             def descriptionOfObject = 'Description'
108             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
109             def response = performTestRequest()
110         then: 'an HTTP Not Found response is returned with correct message and details'
111             assertTestResponse(response, NOT_FOUND, 'Object not found',
112                     'Description does not exist in dataspace MyDataSpace.')
113     }
114
115     @Unroll
116     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
117         when: 'no data found CPS exception is thrown by the service'
118             setupTestException(exceptionThrown)
119             def response = performTestRequest()
120         then: 'an HTTP Bad Request response is returned with correct message an details'
121             assertTestResponse(response, BAD_REQUEST,
122                     "Duplicate ${expectedObjectTypeInMessage}",
123                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
124                             'already exists for dataspace MyDataSpace.')
125         where: 'the following exceptions are thrown'
126             exceptionThrown                                                               || expectedObjectTypeInMessage
127             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
128             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
129     }
130
131     @Unroll
132     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
133         when: 'CPS validation exception is thrown by the service'
134             setupTestException(exceptionThrown)
135             def response = performTestRequest()
136         then: 'an HTTP Bad Request response is returned with correct message and details'
137             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
138         where: 'the following exceptions are thrown'
139             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
140                                 new DataValidationException(errorMessage, errorDetails, null),
141                                 new CpsPathException(errorMessage, errorDetails)]
142     }
143
144     @Unroll
145     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
146         when: 'CPS validation exception is thrown by the service'
147             setupTestException(exceptionThrown)
148             def response = performTestRequest()
149         then: 'an HTTP Conflict response is returned with correct message and details'
150             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
151         where: 'the following exceptions are thrown'
152             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
153                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
154     }
155
156     /*
157      * NB. The test uses 'get anchors' endpoint and associated service method invocation
158      * to test the exception handling. The endpoint chosen is not a subject of test.
159      */
160     def setupTestException(exception) {
161         mockCpsAdminService.getAnchors(_) >> { throw exception }
162     }
163
164     def performTestRequest() {
165         return mvc.perform(
166                 get("$basePath/v1/dataspaces/dataspace-name/anchors"))
167                 .andReturn().response
168     }
169
170     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
171         assert response.status == expectedStatus.value()
172         def content = new JsonSlurper().parseText(response.contentAsString)
173         assert content['status'] == expectedStatus.toString()
174         assert content['message'] == expectedErrorMessage
175         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
176     }
177 }