Introduce Instrumentation
[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.CpsAdminService
30 import org.onap.cps.api.CpsDataService
31 import org.onap.cps.api.CpsModuleService
32 import org.onap.cps.api.CpsQueryService
33 import org.onap.cps.rest.controller.CpsRestInputMapper
34 import org.onap.cps.spi.exceptions.AlreadyDefinedException
35 import org.onap.cps.spi.exceptions.CpsException
36 import org.onap.cps.spi.exceptions.CpsPathException
37 import org.onap.cps.spi.exceptions.DataInUseException
38 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
39 import org.onap.cps.spi.exceptions.DataValidationException
40 import org.onap.cps.spi.exceptions.ModelValidationException
41 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
42 import org.onap.cps.spi.exceptions.SchemaSetInUseException
43 import org.onap.cps.spi.exceptions.DataspaceInUseException
44 import org.onap.cps.utils.JsonObjectMapper
45 import org.onap.cps.utils.PrefixResolver
46 import org.spockframework.spring.SpringBean
47 import org.springframework.beans.factory.annotation.Autowired
48 import org.springframework.beans.factory.annotation.Value
49 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
50 import org.springframework.http.MediaType
51 import org.springframework.test.web.servlet.MockMvc
52 import spock.lang.Shared
53 import spock.lang.Specification
54
55 import static org.springframework.http.HttpStatus.BAD_REQUEST
56 import static org.springframework.http.HttpStatus.CONFLICT
57 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
58 import static org.springframework.http.HttpStatus.NOT_FOUND
59 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
61
62 @WebMvcTest
63 class CpsRestExceptionHandlerSpec extends Specification {
64
65     @SpringBean
66     CpsAdminService mockCpsAdminService = Stub()
67
68     @SpringBean
69     CpsModuleService mockCpsModuleService = Stub()
70
71     @SpringBean
72     CpsDataService mockCpsDataService = Stub()
73
74     @SpringBean
75     CpsQueryService mockCpsQueryService = Stub()
76
77     @SpringBean
78     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
79
80     @SpringBean
81     CpsRestInputMapper cpsRestInputMapper = Stub()
82
83     @SpringBean
84     PrefixResolver prefixResolver = Mock()
85
86     @Autowired
87     MockMvc mvc
88
89     @Value('${rest.api.cps-base-path}')
90     def basePath
91
92     @Shared
93     def errorMessage = 'some error message'
94     @Shared
95     def errorDetails = 'some error details'
96     @Shared
97     def dataspaceName = 'MyDataSpace'
98     @Shared
99     def existingObjectName = 'MyAdminObject'
100
101
102     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
103         when: 'runtime exception is thrown by the service'
104             setupTestException(new IllegalStateException(errorMessage))
105             def response = performTestRequest()
106         then: 'an HTTP Internal Server Error response is returned with correct message and details'
107             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
108     }
109
110     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
111         when: 'generic CPS exception is thrown by the service'
112             setupTestException(new CpsException(errorMessage, errorDetails))
113             def response = performTestRequest()
114         then: 'an HTTP Internal Server Error response is returned with correct message and details'
115             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
116     }
117
118     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
119         when: 'no data found CPS exception is thrown by the service'
120             def dataspaceName = 'MyDataSpace'
121             def descriptionOfObject = 'Description'
122             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
123             def response = performTestRequest()
124         then: 'an HTTP Not Found response is returned with correct message and details'
125             assertTestResponse(response, NOT_FOUND, 'Object not found',
126                 'Description does not exist in dataspace MyDataSpace.')
127     }
128
129     def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
130         when: 'AlreadyDefinedException exception is thrown by the service'
131             setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
132             def response = performTestRequest()
133         then: 'a HTTP conflict response is returned with correct message an details'
134             assertTestResponse(response, CONFLICT,
135                 "Already defined exception",
136                 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
137     }
138
139     def 'Request with a schema set in use exception returns HTTP Status Conflict.'() {
140         when: 'Schema set in use exception is thrown by the service'
141             setupTestException(new SchemaSetInUseException(dataspaceName, existingObjectName))
142             def response = performTestRequest()
143         then: 'a HTTP conflict response is returned with correct message an details'
144             assertTestResponse(response, CONFLICT,
145                 "Schema Set is being used.",
146                 "Schema Set with name ${existingObjectName} in dataspace ${dataspaceName} is having Anchor records associated.")
147     }
148
149     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
150         when: '#exceptionThrown.class.simpleName is thrown by the service'
151             setupTestException(exceptionThrown)
152             def response = performTestRequest()
153         then: 'an HTTP Bad Request response is returned with correct message and details'
154             assertTestResponse(response, BAD_REQUEST, expectedErrorMessage, expectedErrorDetails)
155         where: 'the following exceptions are thrown'
156             exceptionThrown                                                || expectedErrorMessage           | expectedErrorDetails
157             new ModelValidationException(errorMessage, errorDetails, null) || errorMessage                   | errorDetails
158             new DataValidationException(errorMessage, errorDetails, null)  || errorMessage                   | errorDetails
159             new CpsPathException(errorDetails)                             || CpsPathException.ERROR_MESSAGE | errorDetails
160     }
161
162     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
163         when: 'CPS validation exception is thrown by the service'
164             setupTestException(exceptionThrown)
165             def response = performTestRequest()
166         then: 'an HTTP Conflict response is returned with correct message and details'
167             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
168         where: 'the following exceptions are thrown'
169             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
170                                 new SchemaSetInUseException(dataspaceName, existingObjectName),
171                                 new DataspaceInUseException(dataspaceName, errorDetails)]
172     }
173
174     /*
175      * NB. This method tests the expected behavior for POST request only;
176      * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
177      */
178
179     def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
180         given: '#exception is thrown the service indicating data is not found'
181             mockCpsDataService.saveData(*_) >> { throw exceptionThrown }
182         when: 'data update request is performed'
183             def response = mvc.perform(
184                 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
185                     .contentType(MediaType.APPLICATION_JSON)
186                     .param('xpath', 'parent node xpath')
187                     .content('{"some-key" : "some-value"}')
188             ).andReturn().response
189         then: 'response code indicates bad input parameters'
190             response.status == BAD_REQUEST.value()
191         where: 'the following exceptions are thrown'
192             exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
193     }
194
195     /*
196      * NB. The test uses 'get anchors' endpoint and associated service method invocation
197      * to test the exception handling. The endpoint chosen is not a subject of test.
198      */
199
200     def setupTestException(exception) {
201         mockCpsAdminService.getAnchors(_) >> { throw exception }
202     }
203
204     def performTestRequest() {
205         return mvc.perform(
206             get("$basePath/v1/dataspaces/dataspace-name/anchors"))
207             .andReturn().response
208     }
209
210     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
211         assert response.status == expectedStatus.value()
212         def content = new JsonSlurper().parseText(response.contentAsString)
213         assert content['status'] == expectedStatus.toString()
214         assert content['message'] == expectedErrorMessage
215         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
216     }
217 }