Merge "Create schema set REST API and service level"
[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  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.rest.exceptions
21
22 import groovy.json.JsonSlurper
23 import org.modelmapper.ModelMapper
24 import org.onap.cps.api.CpsAdminService
25 import org.onap.cps.api.CpsModuleService
26 import org.onap.cps.spi.exceptions.AnchorAlreadyDefinedException
27 import org.onap.cps.spi.exceptions.CpsException
28 import org.onap.cps.spi.exceptions.DataValidationException
29 import org.onap.cps.spi.exceptions.ModelValidationException
30 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
31 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
32 import org.spockframework.spring.SpringBean
33 import org.springframework.beans.factory.annotation.Autowired
34 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
35 import org.springframework.test.web.servlet.MockMvc
36 import spock.lang.Shared
37 import spock.lang.Specification
38 import spock.lang.Unroll
39
40 import static org.springframework.http.HttpStatus.BAD_REQUEST
41 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
42 import static org.springframework.http.HttpStatus.NOT_FOUND
43 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
44
45 @WebMvcTest
46 class CpsRestExceptionHandlerSpec extends Specification {
47
48     @SpringBean
49     CpsAdminService mockCpsAdminService = Mock()
50
51     @SpringBean
52     CpsModuleService mockCpsModuleService = Mock()
53
54     @SpringBean
55     ModelMapper modelMapper = Mock()
56
57     @Autowired
58     MockMvc mvc
59
60     @Shared
61     def errorMessage = 'some error message'
62     @Shared
63     def errorDetails = 'some error details'
64     @Shared
65     def dataspaceName = 'MyDataSpace'
66     @Shared
67     def existingObjectName = 'MyAdminObject'
68
69
70     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
71
72         when: 'runtime exception is thrown by the service'
73             setupTestException(new IllegalStateException(errorMessage))
74             def response = performTestRequest()
75
76         then: 'an HTTP Internal Server Error response is returned with correct message and details'
77             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
78     }
79
80     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
81
82         when: 'generic CPS exception is thrown by the service'
83             setupTestException(new CpsException(errorMessage, errorDetails))
84             def response = performTestRequest()
85
86         then: 'an HTTP Internal Server Error response is returned with correct message and details'
87             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
88     }
89
90     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
91
92         when: 'no data found CPS exception is thrown by the service'
93             def dataspaceName = 'MyDataSpace'
94             def descriptionOfObject = 'Description'
95             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
96             def response = performTestRequest()
97
98         then: 'an HTTP Not Found response is returned with correct message and details'
99             assertTestResponse(response, NOT_FOUND, 'Object not found',
100                     'Description does not exist in dataspace MyDataSpace.')
101     }
102
103     @Unroll
104     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
105
106         when: 'no data found CPS exception is thrown by the service'
107             setupTestException(exceptionThrown)
108             def response = performTestRequest()
109
110         then: 'an HTTP Bad Request response is returned with correct message an details'
111             assertTestResponse(response, BAD_REQUEST,
112                     "Duplicate ${expectedObjectTypeInMessage}",
113                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
114                             'already exists for dataspace MyDataSpace.')
115         where: 'the following exceptions are thrown'
116             exceptionThrown                                                               || expectedObjectTypeInMessage
117             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
118             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
119     }
120
121     @Unroll
122     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
123
124         when: 'CPS validation exception is thrown by the service'
125             setupTestException(exceptionThrown)
126             def response = performTestRequest()
127
128         then: 'an HTTP Bad Request response is returned with correct message and details'
129             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
130
131         where: 'the following exceptions are thrown'
132             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
133                                 new DataValidationException(errorMessage, errorDetails, null)]
134     }
135
136     /*
137      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
138      * to test the exception handling. The endpoint chosen is not a subject of test.
139      */
140
141     def setupTestException(exception) {
142         mockCpsAdminService.getAnchors(_) >> { throw exception}
143     }
144
145     def performTestRequest() {
146         return mvc.perform(get('/v1/dataspaces/dataspace-name/anchors')).andReturn().response
147     }
148
149     void assertTestResponse(response, expectedStatus,
150                             expectedErrorMessage, expectedErrorDetails) {
151         assert response.status == expectedStatus.value()
152         def content = new JsonSlurper().parseText(response.contentAsString)
153         assert content['status'] == expectedStatus.toString()
154         assert content['message'] == expectedErrorMessage
155         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
156     }
157 }