e97c586561fd9587e3d0e7b2b86774a03fa41eac
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 highstreet technologies GmbH
4  *  Modifications Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
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  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.rest.controller
23
24 import groovy.json.JsonSlurper
25 import org.mapstruct.factory.Mappers
26 import org.onap.cps.TestUtils
27 import org.onap.cps.api.exceptions.AlreadyDefinedException
28 import org.onap.cps.api.exceptions.CpsException
29 import org.onap.cps.api.exceptions.DataNodeNotFoundException
30 import org.onap.cps.api.exceptions.DataValidationException
31 import org.onap.cps.ncmp.api.data.exceptions.InvalidOperationException
32 import org.onap.cps.ncmp.api.data.exceptions.OperationNotSupportedException
33 import org.onap.cps.ncmp.api.exceptions.DmiClientRequestException
34 import org.onap.cps.ncmp.api.exceptions.DmiRequestException
35 import org.onap.cps.ncmp.api.exceptions.PayloadTooLargeException
36 import org.onap.cps.ncmp.api.exceptions.PolicyExecutorException
37 import org.onap.cps.ncmp.api.exceptions.ServerNcmpException
38 import org.onap.cps.ncmp.impl.NetworkCmProxyInventoryFacadeImpl
39 import org.onap.cps.ncmp.impl.data.NcmpCachedResourceRequestHandler
40 import org.onap.cps.ncmp.impl.data.NcmpPassthroughResourceRequestHandler
41 import org.onap.cps.ncmp.impl.data.NetworkCmProxyFacade
42 import org.onap.cps.ncmp.impl.data.policyexecutor.PolicyExecutor
43 import org.onap.cps.ncmp.impl.dmi.DmiRestClient
44 import org.onap.cps.ncmp.impl.inventory.InventoryPersistence
45 import org.onap.cps.ncmp.impl.provmns.ParametersBuilder
46 import org.onap.cps.ncmp.impl.utils.AlternateIdMatcher
47 import org.onap.cps.ncmp.rest.util.CmHandleStateMapper
48 import org.onap.cps.ncmp.rest.util.DataOperationRequestMapper
49 import org.onap.cps.ncmp.rest.util.DeprecationHelper
50 import org.onap.cps.ncmp.rest.util.NcmpRestInputMapper
51 import org.onap.cps.ncmp.rest.util.RestOutputCmHandleMapper
52 import org.onap.cps.utils.JsonObjectMapper
53 import org.spockframework.spring.SpringBean
54 import org.springframework.beans.factory.annotation.Autowired
55 import org.springframework.beans.factory.annotation.Value
56 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
57 import org.springframework.http.MediaType
58 import org.springframework.test.web.servlet.MockMvc
59 import spock.lang.Shared
60 import spock.lang.Specification
61
62 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNABLE_TO_READ_RESOURCE_DATA
63 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
64 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
65 import static org.springframework.http.HttpStatus.BAD_GATEWAY
66 import static org.springframework.http.HttpStatus.BAD_REQUEST
67 import static org.springframework.http.HttpStatus.CONFLICT
68 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
69 import static org.springframework.http.HttpStatus.NOT_FOUND
70 import static org.springframework.http.HttpStatus.PAYLOAD_TOO_LARGE
71 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
72 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
73
74 @WebMvcTest
75 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
76
77     @Autowired
78     MockMvc mvc
79
80     @SpringBean
81     NetworkCmProxyFacade mockNetworkCmProxyFacade = Mock()
82
83     @SpringBean
84     NetworkCmProxyInventoryFacadeImpl mockNetworkCmProxyInventoryFacade = Mock()
85
86     @SpringBean
87     InventoryPersistence mockInventoryPersistence = Mock()
88
89     @SpringBean
90     JsonObjectMapper stubbedJsonObjectMapper = Stub()
91
92     @SpringBean
93     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
94
95     @SpringBean
96     CmHandleStateMapper cmHandleStateMapper = Mappers.getMapper(CmHandleStateMapper)
97
98     @SpringBean
99     DataOperationRequestMapper dataOperationRequestMapper = Mappers.getMapper(DataOperationRequestMapper)
100
101     @SpringBean
102     DeprecationHelper stubbedDeprecationHelper = Stub()
103
104     @SpringBean
105     NcmpCachedResourceRequestHandler stubbedNcmpCachedResourceRequestHandler = Stub()
106
107     @SpringBean
108     NcmpPassthroughResourceRequestHandler StubbedNcmpPassthroughResourceRequestHandler = Stub()
109
110     @SpringBean
111     DataJobControllerForTest stubbedDataJobControllerForTest = Stub()
112
113     @SpringBean
114     RestOutputCmHandleMapper mockRestOutputCmHandleMapper = Mock()
115
116     @SpringBean
117     ParametersBuilder mockProvMnSParametersMapper = Mock()
118
119     @SpringBean
120     ProvMnSController mockProvMnsController = Mock()
121
122     @SpringBean
123     AlternateIdMatcher alternateIdMatcher = Mock()
124
125     @SpringBean
126     DmiRestClient dmiRestClient = Mock()
127
128     @SpringBean
129     PolicyExecutor policyExecutor = Mock()
130
131     @Value('${rest.api.ncmp-base-path}')
132     def basePathNcmp
133
134     @Value('${rest.api.ncmp-inventory-base-path}')
135     def basePathNcmpInventory
136
137     def dataNodeBaseEndpointNcmp
138     def dataNodeBaseEndpointNcmpInventory
139
140     @Shared
141     def sampleErrorMessage = 'some error message'
142     @Shared
143     def sampleErrorDetails = 'some error details'
144
145     def setup() {
146         dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
147         dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
148     }
149
150     def 'Get request with #scenario exception returns correct HTTP Status with #scenario exception'() {
151         when: 'an exception is thrown by the service'
152             setupTestException(exception, NCMP)
153             def response = performTestRequest(NCMP)
154         then: 'an HTTP response is returned with correct message and details'
155             assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
156         where:
157             scenario                | exception                                                                 || expectedErrorCode     | expectedErrorMessage        | expectedErrorDetails
158             'CPS'                   | new CpsException(sampleErrorMessage, sampleErrorDetails)                  || INTERNAL_SERVER_ERROR | sampleErrorMessage          | sampleErrorDetails
159             'NCMP-server'           | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails)           || INTERNAL_SERVER_ERROR | sampleErrorMessage          | null
160             'DMI Request'           | new DmiRequestException(sampleErrorMessage, sampleErrorDetails)           || BAD_REQUEST           | sampleErrorMessage          | null
161             'Invalid Operation'     | new InvalidOperationException('some reason')                              || BAD_REQUEST           | 'some reason'               | null
162             'Unsupported Operation' | new OperationNotSupportedException('not yet')                             || BAD_REQUEST           | 'not yet'                   | null
163             'DataNode Validation'   | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName')          || NOT_FOUND             | 'DataNode not found'        | null
164             'other'                 | new IllegalStateException(sampleErrorMessage)                             || INTERNAL_SERVER_ERROR | sampleErrorMessage          | null
165             'Data Node Not Found'   | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName')          || NOT_FOUND             | 'DataNode not found'        | 'DataNode not found'
166             'Existing entry'        | new AlreadyDefinedException('name',null)                                  || CONFLICT              | 'Already defined exception' | 'name already exists'
167             'Existing entries'      | AlreadyDefinedException.forDataNodes(['A', 'B'], 'myAnchorName')          || CONFLICT              | 'Already defined exception' | '2 data node(s) already exist'
168             'Operation too large'   | new PayloadTooLargeException(sampleErrorMessage)                          || PAYLOAD_TOO_LARGE     | sampleErrorMessage          | 'Check logs'
169             'Policy Executor'       | new PolicyExecutorException(sampleErrorMessage, sampleErrorDetails, null) || CONFLICT              | sampleErrorMessage          | sampleErrorDetails
170     }
171
172     def 'Post request with exception returns correct HTTP Status.'() {
173         given: 'the service throws data validation exception'
174             def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
175             setupTestException(exception, NCMPINVENTORY)
176         when: 'the HTTP request is made'
177             def response = performTestRequest(NCMPINVENTORY)
178         then: 'an HTTP response is returned with correct message and details'
179             assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
180     }
181
182     def 'Failing DMI Request - passthrough scenario'() {
183         given: 'failing DMI request'
184             setupTestException(new DmiClientRequestException(400, 'Error Message Details NCMP', 'Bad Request from DMI', UNABLE_TO_READ_RESOURCE_DATA), NCMP)
185         when: 'the DMI request is executed'
186             def response = performTestRequest(NCMP)
187         then: 'NCMP service responds with 502 Bad Gateway status'
188             assert response.status == BAD_GATEWAY.value()
189         and: 'the NCMP response also contains the original DMI response details'
190             response.contentAsString.contains('400')
191             response.contentAsString.contains('Bad Request from DMI')
192     }
193
194     def setupTestException(exception, apiType) {
195         if (NCMP == apiType) {
196             mockNetworkCmProxyInventoryFacade.getYangResourcesModuleReferences(*_) >> { throw exception }
197         }
198         mockNetworkCmProxyInventoryFacade.updateDmiRegistration(*_) >> { throw exception }
199     }
200
201     def performTestRequest(apiType) {
202         if (NCMP == apiType) {
203             return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
204         }
205         def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
206         return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
207     }
208
209     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
210         assert response.status == expectedStatus.value()
211         def content = new JsonSlurper().parseText(response.contentAsString)
212         assert content['status'].toString().contains(expectedStatus.toString())
213         assert expectedErrorMessage == null || content['message'].toString().contains(expectedErrorMessage)
214         assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
215     }
216
217     enum ApiType { NCMP,  NCMPINVENTORY  }
218 }