Few Sonar Fixes
[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.spi.exceptions.AnchorAlreadyDefinedException
26 import org.onap.cps.spi.exceptions.CpsException
27 import org.onap.cps.spi.exceptions.DataValidationException
28 import org.onap.cps.spi.exceptions.NotFoundInDataspaceException
29 import org.onap.cps.spi.exceptions.ModelValidationException
30 import org.onap.cps.spi.exceptions.SchemaSetAlreadyDefinedException
31 import org.spockframework.spring.SpringBean
32 import org.springframework.beans.factory.annotation.Autowired
33 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
34 import org.springframework.test.web.servlet.MockMvc
35 import spock.lang.Shared
36 import spock.lang.Specification
37 import spock.lang.Unroll
38
39 import static org.springframework.http.HttpStatus.BAD_REQUEST
40 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
41 import static org.springframework.http.HttpStatus.NOT_FOUND
42 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
43
44 @WebMvcTest
45 class CpsRestExceptionHandlerSpec extends Specification {
46
47     @SpringBean
48     CpsAdminService mockCpsAdminService = Mock()
49
50     @SpringBean
51     ModelMapper modelMapper = Mock()
52
53     @Autowired
54     MockMvc mvc
55
56     @Shared
57     def errorMessage = 'some error message'
58     @Shared
59     def errorDetails = 'some error details'
60     @Shared
61     def dataspaceName = 'MyDataSpace'
62     @Shared
63     def existingObjectName = 'MyAdminObject'
64
65
66     def 'Get request with runtime exception returns HTTP Status Internal Server Error'() {
67
68         when: 'runtime exception is thrown by the service'
69             setupTestException(new IllegalStateException(errorMessage))
70             def response = performTestRequest()
71
72         then: 'an HTTP Internal Server Error response is returned with correct message and details'
73             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, null)
74     }
75
76     def 'Get request with generic CPS exception returns HTTP Status Internal Server Error'() {
77
78         when: 'generic CPS exception is thrown by the service'
79             setupTestException(new CpsException(errorMessage, errorDetails))
80             def response = performTestRequest()
81
82         then: 'an HTTP Internal Server Error response is returned with correct message and details'
83             assertTestResponse(response, INTERNAL_SERVER_ERROR, errorMessage, errorDetails)
84     }
85
86     def 'Get request with no data found CPS exception returns HTTP Status Not Found'() {
87
88         when: 'no data found CPS exception is thrown by the service'
89             def dataspaceName = 'MyDataSpace'
90             def descriptionOfObject = 'Description'
91             setupTestException(new NotFoundInDataspaceException(dataspaceName, descriptionOfObject))
92             def response = performTestRequest()
93
94         then: 'an HTTP Not Found response is returned with correct message and details'
95             assertTestResponse(response, NOT_FOUND, 'Object not found',
96                     'Description does not exist in dataspace MyDataSpace.')
97     }
98
99     @Unroll
100     def 'request with an expectedObjectTypeInMessage object already defined exception returns HTTP Status Bad Request'() {
101
102         when: 'no data found CPS exception is thrown by the service'
103             setupTestException(exceptionThrown)
104             def response = performTestRequest()
105
106         then: 'an HTTP Bad Request response is returned with correct message an details'
107             assertTestResponse(response, BAD_REQUEST,
108                     "Duplicate ${expectedObjectTypeInMessage}",
109                     "${expectedObjectTypeInMessage} with name ${existingObjectName} " +
110                             'already exists for dataspace MyDataSpace.')
111         where: 'the following exceptions are thrown'
112             exceptionThrown                                                               || expectedObjectTypeInMessage
113             new SchemaSetAlreadyDefinedException(dataspaceName, existingObjectName, null) || 'Schema Set'
114             new AnchorAlreadyDefinedException(dataspaceName, existingObjectName, null)    || 'Anchor'
115     }
116
117     @Unroll
118     def 'Get request with a #exceptionThrown.class.simpleName returns HTTP Status Bad Request'() {
119
120         when: 'CPS validation exception is thrown by the service'
121             setupTestException(exceptionThrown)
122             def response = performTestRequest()
123
124         then: 'an HTTP Bad Request response is returned with correct message and details'
125             assertTestResponse(response, BAD_REQUEST, errorMessage, errorDetails)
126
127         where: 'the following exceptions are thrown'
128             exceptionThrown << [new ModelValidationException(errorMessage, errorDetails, null),
129                                 new DataValidationException(errorMessage, errorDetails, null)]
130     }
131
132     /*
133      * NB. The test uses 'get JSON by id' endpoint and associated service method invocation
134      * to test the exception handling. The endpoint chosen is not a subject of test.
135      */
136
137     def setupTestException(exception) {
138         mockCpsAdminService.getAnchors(_) >> { throw exception}
139     }
140
141     def performTestRequest() {
142         return mvc.perform(get('/v1/dataspaces/dataspace-name/anchors')).andReturn().response
143     }
144
145     void assertTestResponse(response, expectedStatus,
146                             expectedErrorMessage, expectedErrorDetails) {
147         assert response.status == expectedStatus.value()
148         def content = new JsonSlurper().parseText(response.contentAsString)
149         assert content['status'] == expectedStatus.toString()
150         assert content['message'] == expectedErrorMessage
151         assert expectedErrorDetails == null || content['details'] == expectedErrorDetails
152     }
153 }