Rest & Java API layer - Query Datanodes using cpsPath that contains contains a leaf...
[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  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.rest.exceptions
22
23 import groovy.json.JsonSlurper
24 import org.modelmapper.ModelMapper
25 import org.onap.cps.api.CpsAdminService
26 import org.onap.cps.api.CpsDataService
27 import org.onap.cps.api.CpsModuleService
28 import org.onap.cps.api.CpsQueryService
29 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
30 import org.onap.cps.spi.exceptions.CpsException
31 import org.onap.cps.spi.exceptions.DataInUseException
32 import org.onap.cps.spi.exceptions.DataValidationException
33 import org.onap.cps.spi.exceptions.ModelValidationException
34 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
35 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
36 import org.onap.cps.spi.exceptions.SchemaSetInUseException
37 import org.spockframework.spring.SpringBean
38 import org.springframework.beans.factory.annotation.Autowired
39 import org.springframework.beans.factory.annotation.Value
40 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
41 import org.springframework.test.web.servlet.MockMvc
42 import spock.lang.Shared
43 import spock.lang.Specification
44 import spock.lang.Unroll
45
46 import static org.springframework.http.HttpStatus.BAD_REQUEST
47 import static org.springframework.http.HttpStatus.CONFLICT
48 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
49 import static org.springframework.http.HttpStatus.NOT_FOUND
50 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
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
88         when: 'runtime exception is thrown by the service'
89             setupTestException(new IllegalStateException(errorMessage))
90             def response = performTestRequest()
91
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
98         when: 'generic CPS exception is thrown by the service'
99             setupTestException(new CpsException(errorMessage, errorDetails))
100             def response = performTestRequest()
101
102         then: 'an HTTP Internal Server Error response is returned with correct message and details'
103             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
104     }
105
106     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
107
108         when: 'no data found CPS exception is thrown by the service'
109             def dataspaceName = 'MyDataSpace'
110             def descriptionOfObject = 'Description'
111             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
112             def response = performTestRequest()
113
114         then: 'an HTTP Not Found response is returned with correct message and details'
115             assertTestResponse(response, NOT_FOUND, 'Object not found',
116                     'Description does not exist in dataspace MyDataSpace.')
117     }
118
119     @Unroll
120     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
121
122         when: 'no data found CPS exception is thrown by the service'
123             setupTestException(exceptionThrown)
124             def response = performTestRequest()
125
126         then: 'an HTTP Bad Request response is returned with correct message an details'
127             assertTestResponse(response, BAD_REQUEST,
128                     "Duplicate ${expectedObjectTypeInMessage}",
129                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
130                             'already exists for dataspace MyDataSpace.')
131         where: 'the following exceptions are thrown'
132             exceptionThrown                                                               || expectedObjectTypeInMessage
133             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
134             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
135     }
136
137     @Unroll
138     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
139
140         when: 'CPS validation exception is thrown by the service'
141             setupTestException(exceptionThrown)
142             def response = performTestRequest()
143
144         then: 'an HTTP Bad Request response is returned with correct message and details'
145             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
146
147         where: 'the following exceptions are thrown'
148             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
149                                 new DataValidationException(errorMessage, errorDetails, null)]
150     }
151
152     @Unroll
153     def 'Delete request with a #exceptionThrown.class.simpleName returns HTTP Status Conflict'() {
154
155         when: 'CPS validation exception is thrown by the service'
156             setupTestException(exceptionThrown)
157             def response = performTestRequest()
158
159         then: 'an HTTP Conflict response is returned with correct message and details'
160             assertTestResponse(response, CONFLICT, exceptionThrown.getMessage(), exceptionThrown.getDetails())
161
162         where: 'the following exceptions are thrown'
163             exceptionThrown << [new DataInUseException(dataspaceName, existingObjectName),
164                                 new SchemaSetInUseException(dataspaceName, existingObjectName)]
165     }
166
167     /*
168      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
169      * to test the exception handling. The endpoint chosen is not a subject of test.
170      */
171
172     def setupTestException(exception) {
173         mockCpsAdminService.getAnchors(_) >> { throw exception}
174     }
175
176     def performTestRequest() {
177         return mvc.perform(get("$basePath/v1/dataspaces/dataspace-name/anchors")).andReturn().response
178     }
179
180     void assertTestResponse(response, expectedStatus,
181                             expectedErrorMessage, expectedErrorDetails) {
182         assert response.status == expectedStatus.value()
183         def content = new JsonSlurper().parseText(response.contentAsString)
184         assert content['status'] == expectedStatus.toString()
185         assert content['message'] == expectedErrorMessage
186         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
187     }
188 }