Remove the dependency-cycle between beans
[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  *  Modifications Copyright (C) 2021-2023 Nordix Foundation
5  *  Modifications Copyright (C) 2021 Bell Canada.
6  *  Modifications Copyright (C) 2022 TechMahindra Ltd.
7  *  Modifications Copyright (C) 2022 Deutsche Telekom AG
8  *  ================================================================================
9  *  Licensed under the Apache License, Version 2.0 (the "License");
10  *  you may not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *        http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS,
17  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  *
21  *  SPDX-License-Identifier: Apache-2.0
22  *  ============LICENSE_END=========================================================
23  */
24
25 package org.onap.cps.rest.exceptions
26
27 import com.fasterxml.jackson.databind.ObjectMapper
28 import groovy.json.JsonSlurper
29 import org.onap.cps.api.CpsDataspaceService
30 import org.onap.cps.api.CpsAnchorService
31 import org.onap.cps.api.CpsDataService
32 import org.onap.cps.api.CpsModuleService
33 import org.onap.cps.api.CpsQueryService
34 import org.onap.cps.rest.controller.CpsRestInputMapper
35 import org.onap.cps.spi.exceptions.AlreadyDefinedException
36 import org.onap.cps.spi.exceptions.CpsException
37 import org.onap.cps.spi.exceptions.CpsPathException
38 import org.onap.cps.spi.exceptions.DataInUseException
39 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
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.onap.cps.spi.exceptions.DataspaceInUseException
45 import org.onap.cps.utils.JsonObjectMapper
46 import org.onap.cps.utils.PrefixResolver
47 import org.spockframework.spring.SpringBean
48 import org.springframework.beans.factory.annotation.Autowired
49 import org.springframework.beans.factory.annotation.Value
50 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
51 import org.springframework.http.MediaType
52 import org.springframework.test.web.servlet.MockMvc
53 import spock.lang.Shared
54 import spock.lang.Specification
55
56 import static org.springframework.http.HttpStatus.BAD_REQUEST
57 import static org.springframework.http.HttpStatus.CONFLICT
58 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
59 import static org.springframework.http.HttpStatus.NOT_FOUND
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
61 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
62
63 @WebMvcTest
64 class CpsRestExceptionHandlerSpec extends Specification {
65
66     @SpringBean
67     CpsDataspaceService mockCpsAdminService = Stub()
68
69     @SpringBean
70     CpsAnchorService mockCpsAnchorService = Stub()
71
72     @SpringBean
73     CpsModuleService mockCpsModuleService = Stub()
74
75     @SpringBean
76     CpsDataService mockCpsDataService = Stub()
77
78     @SpringBean
79     CpsQueryService mockCpsQueryService = Stub()
80
81     @SpringBean
82     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
83
84     @SpringBean
85     CpsRestInputMapper cpsRestInputMapper = Stub()
86
87     @SpringBean
88     PrefixResolver prefixResolver = Mock()
89
90     @Autowired
91     MockMvc mvc
92
93     @Value('${rest.api.cps-base-path}')
94     def basePath
95
96     @Shared
97     def errorMessage = 'some error message'
98     @Shared
99     def errorDetails = 'some error details'
100     @Shared
101     def dataspaceName = 'MyDataSpace'
102     @Shared
103     def existingObjectName = 'MyAdminObject'
104
105
106     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
107         when: 'runtime exception is thrown by the service'
108             setupTestException(new IllegalStateException(errorMessage))
109             def response = performTestRequest()
110         then: 'an HTTP Internal Server Error response is returned with correct message and details'
111             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
112     }
113
114     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
115         when: 'generic CPS exception is thrown by the service'
116             setupTestException(new CpsException(errorMessage, errorDetails))
117             def response = performTestRequest()
118         then: 'an HTTP Internal Server Error response is returned with correct message and details'
119             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
120     }
121
122     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
123         when: 'no data found CPS exception is thrown by the service'
124             def dataspaceName = 'MyDataSpace'
125             def descriptionOfObject = 'Description'
126             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
127             def response = performTestRequest()
128         then: 'an HTTP Not Found response is returned with correct message and details'
129             assertTestResponse(response, NOT_FOUND, 'Object not found',
130                 'Description does not exist in dataspace MyDataSpace.')
131     }
132
133     def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
134         when: 'AlreadyDefinedException exception is thrown by the service'
135             setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
136             def response = performTestRequest()
137         then: 'a HTTP conflict response is returned with correct message an details'
138             assertTestResponse(response, CONFLICT,
139                 "Already defined exception",
140                 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
141     }
142
143     def 'Request with a schema set in use exception returns HTTP Status Conflict.'() {
144         when: 'Schema set in use exception is thrown by the service'
145             setupTestException(new SchemaSetInUseException(dataspaceName, existingObjectName))
146             def response = performTestRequest()
147         then: 'a HTTP conflict response is returned with correct message an details'
148             assertTestResponse(response, CONFLICT,
149                 "Schema Set is being used.",
150                 "Schema Set with name ${existingObjectName} in dataspace ${dataspaceName} is having Anchor records associated.")
151     }
152
153     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
154         when: '#exceptionThrown.class.simpleName is thrown by the service'
155             setupTestException(exceptionThrown)
156             def response = performTestRequest()
157         then: 'an HTTP Bad Request response is returned with correct message and details'
158             assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
159         where: 'the following exceptions are thrown'
160             exceptionThrown                                                || expectedErrorMessage           | expectedErrorDetails
161             new ModelValidationException(errorMessage, errorDetails, null) || errorMessage                   | errorDetails
162             new DataValidationException(errorMessage, errorDetails, null)  || errorMessage                   | errorDetails
163             new CpsPathException(errorDetails)                             || CpsPathException.ERROR_MESSAGE | errorDetails
164     }
165
166     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
167         when: 'CPS validation exception is thrown by the service'
168             setupTestException(exceptionThrown)
169             def response = performTestRequest()
170         then: 'an HTTP Conflict response is returned with correct message and details'
171             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
172         where: 'the following exceptions are thrown'
173             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
174                                 new SchemaSetInUseException(dataspaceName, existingObjectName),
175                                 new DataspaceInUseException(dataspaceName, errorDetails)]
176     }
177
178     /*
179      * NB. This method tests the expected behavior for POST request only;
180      * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
181      */
182
183     def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
184         given: '#exception is thrown the service indicating data is not found'
185             mockCpsDataService.saveData(*_) >> { throw exceptionThrown }
186         when: 'data update request is performed'
187             def response = mvc.perform(
188                 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
189                     .contentType(MediaType.APPLICATION_JSON)
190                     .param('xpath', 'parent node xpath')
191                     .content('{"some-key" : "some-value"}')
192             ).andReturn().response
193         then: 'response code indicates bad input parameters'
194             response.status == BAD_REQUEST.value()
195         where: 'the following exceptions are thrown'
196             exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
197     }
198
199     /*
200      * NB. The test uses 'get anchors' endpoint and associated service method invocation
201      * to test the exception handling. The endpoint chosen is not a subject of test.
202      */
203
204     def setupTestException(exception) {
205         mockCpsAnchorService.getAnchors(_) >> { throw exception }
206     }
207
208     def performTestRequest() {
209         return mvc.perform(
210             get("$basePath/v1/dataspaces/dataspace-name/anchors"))
211             .andReturn().response
212     }
213
214     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
215         assert response.status == expectedStatus.value()
216         def content = new JsonSlurper().parseText(response.contentAsString)
217         assert content['status'] == expectedStatus.toString()
218         assert content['message'] == expectedErrorMessage
219         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
220     }
221 }