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