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