a2eaa525e07c0f7f13c93d564232fe694c43be16
[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-2022 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  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.rest.exceptions
24
25 import groovy.json.JsonSlurper
26 import org.modelmapper.ModelMapper
27 import org.onap.cps.api.CpsAdminService
28 import org.onap.cps.api.CpsDataService
29 import org.onap.cps.api.CpsModuleService
30 import org.onap.cps.api.CpsQueryService
31 import org.onap.cps.spi.exceptions.AlreadyDefinedException
32 import org.onap.cps.spi.exceptions.CpsException
33 import org.onap.cps.spi.exceptions.CpsPathException
34 import org.onap.cps.spi.exceptions.DataInUseException
35 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
36 import org.onap.cps.spi.exceptions.DataValidationException
37 import org.onap.cps.spi.exceptions.ModelValidationException
38 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
39 import org.onap.cps.spi.exceptions.SchemaSetInUseException
40 import org.onap.cps.spi.exceptions.DataspaceInUseException
41 import org.onap.cps.utils.JsonObjectMapper
42 import org.spockframework.spring.SpringBean
43 import org.springframework.beans.factory.annotation.Autowired
44 import org.springframework.beans.factory.annotation.Value
45 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
46 import org.springframework.http.MediaType
47 import org.springframework.test.web.servlet.MockMvc
48 import spock.lang.Shared
49 import spock.lang.Specification
50
51 import static org.springframework.http.HttpStatus.BAD_REQUEST
52 import static org.springframework.http.HttpStatus.CONFLICT
53 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
54 import static org.springframework.http.HttpStatus.NOT_FOUND
55 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
56 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
57
58 @WebMvcTest
59 class CpsRestExceptionHandlerSpec extends Specification {
60
61     @SpringBean
62     CpsAdminService mockCpsAdminService = Stub()
63
64     @SpringBean
65     CpsModuleService mockCpsModuleService = Stub()
66
67     @SpringBean
68     CpsDataService mockCpsDataService = Stub()
69
70     @SpringBean
71     CpsQueryService mockCpsQueryService = Stub()
72
73     @SpringBean
74     ModelMapper modelMapper = Stub()
75
76     @SpringBean
77     JsonObjectMapper jsonObjectMapper = Stub()
78
79     @Autowired
80     MockMvc mvc
81
82     @Value('${rest.api.cps-base-path}')
83     def basePath
84
85     @Shared
86     def errorMessage = 'some error message'
87     @Shared
88     def errorDetails = 'some error details'
89     @Shared
90     def dataspaceName = 'MyDataSpace'
91     @Shared
92     def existingObjectName = 'MyAdminObject'
93
94
95     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
96         when: 'runtime exception is thrown by the service'
97             setupTestException(new IllegalStateException(errorMessage))
98             def response = performTestRequest()
99         then: 'an HTTP Internal Server Error response is returned with correct message and details'
100             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
101     }
102
103     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
104         when: 'generic CPS exception is thrown by the service'
105             setupTestException(new CpsException(errorMessage, errorDetails))
106             def response = performTestRequest()
107         then: 'an HTTP Internal Server Error response is returned with correct message and details'
108             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
109     }
110
111     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
112         when: 'no data found CPS exception is thrown by the service'
113             def dataspaceName = 'MyDataSpace'
114             def descriptionOfObject = 'Description'
115             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
116             def response = performTestRequest()
117         then: 'an HTTP Not Found response is returned with correct message and details'
118             assertTestResponse(response, NOT_FOUND, 'Object not found',
119                 'Description does not exist in dataspace MyDataSpace.')
120     }
121
122     def 'Request with an object already defined exception returns HTTP Status Conflict.'() {
123         when: 'AlreadyDefinedException exception is thrown by the service'
124             setupTestException(new AlreadyDefinedException("Anchor", existingObjectName, dataspaceName, new Throwable()))
125             def response = performTestRequest()
126         then: 'a HTTP conflict response is returned with correct message an details'
127             assertTestResponse(response, CONFLICT,
128                 "Already defined exception",
129                 "Anchor with name ${existingObjectName} already exists for ${dataspaceName}.")
130     }
131
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, expectedErrorMessage, expectedErrorDetails)
138         where: 'the following exceptions are thrown'
139             exceptionThrown                                                || expectedErrorMessage           | expectedErrorDetails
140             new ModelValidationException(errorMessage, errorDetails, null) || errorMessage                   | errorDetails
141             new DataValidationException(errorMessage, errorDetails, null)  || errorMessage                   | errorDetails
142             new CpsPathException(errorDetails)                             || CpsPathException.ERROR_MESSAGE | errorDetails
143     }
144
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                                 new DataspaceInUseException(dataspaceName, errorDetails)]
155     }
156
157     /*
158      * NB. This method tests the expected behavior for POST request only;
159      * testing of PUT and PATCH requests omitted due to same NOT 'GET' condition is being used.
160      */
161
162     def 'Post request with #exceptionThrown.class.simpleName returns HTTP Status Bad Request.'() {
163         given: '#exception is thrown the service indicating data is not found'
164             mockCpsDataService.saveData(_, _, _, _, _) >> { throw exceptionThrown }
165         when: 'data update request is performed'
166             def response = mvc.perform(
167                 post("$basePath/v1/dataspaces/dataspace-name/anchors/anchor-name/nodes")
168                     .contentType(MediaType.APPLICATION_JSON)
169                     .param('xpath', 'parent node xpath')
170                     .content(groovy.json.JsonOutput.toJson('{"some-key" : "some-value"}'))
171             ).andReturn().response
172         then: 'response code indicates bad input parameters'
173             response.status == BAD_REQUEST.value()
174         where: 'the following exceptions are thrown'
175             exceptionThrown << [new DataNodeNotFoundException('', ''), new NotFoundInDataspaceException('', '')]
176     }
177
178     /*
179      * NB. The test uses 'get anchors' endpoint and associated service method invocation
180      * to test the exception handling. The endpoint chosen is not a subject of test.
181      */
182
183     def setupTestException(exception) {
184         mockCpsAdminService.getAnchors(_) >> { throw exception }
185     }
186
187     def performTestRequest() {
188         return mvc.perform(
189             get("$basePath/v1/dataspaces/dataspace-name/anchors"))
190             .andReturn().response
191     }
192
193     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
194         assert response.status == expectedStatus.value()
195         def content = new JsonSlurper().parseText(response.contentAsString)
196         assert content['status'] == expectedStatus.toString()
197         assert content['message'] == expectedErrorMessage
198         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
199     }
200 }