7b16df52df1de90bfb03131e959c7288fcc9a9c8
[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.ncmp.api.data.exceptions.InvalidOperationException
28 import org.onap.cps.ncmp.api.data.exceptions.OperationNotSupportedException
29 import org.onap.cps.ncmp.api.exceptions.DmiClientRequestException
30 import org.onap.cps.ncmp.api.exceptions.DmiRequestException
31 import org.onap.cps.ncmp.api.exceptions.PayloadTooLargeException
32 import org.onap.cps.ncmp.api.exceptions.PolicyExecutorException
33 import org.onap.cps.ncmp.api.exceptions.ServerNcmpException
34 import org.onap.cps.ncmp.impl.NetworkCmProxyInventoryFacadeImpl
35 import org.onap.cps.ncmp.impl.data.NcmpCachedResourceRequestHandler
36 import org.onap.cps.ncmp.impl.data.NcmpPassthroughResourceRequestHandler
37 import org.onap.cps.ncmp.impl.data.NetworkCmProxyFacade
38 import org.onap.cps.ncmp.impl.inventory.InventoryPersistence
39 import org.onap.cps.ncmp.rest.util.CmHandleStateMapper
40 import org.onap.cps.ncmp.rest.util.DataOperationRequestMapper
41 import org.onap.cps.ncmp.rest.util.DeprecationHelper
42 import org.onap.cps.ncmp.rest.util.NcmpRestInputMapper
43 import org.onap.cps.api.exceptions.AlreadyDefinedException
44 import org.onap.cps.api.exceptions.CpsException
45 import org.onap.cps.api.exceptions.DataNodeNotFoundException
46 import org.onap.cps.api.exceptions.DataValidationException
47 import org.onap.cps.ncmp.rest.util.RestOutputCmHandleMapper
48 import org.onap.cps.utils.JsonObjectMapper
49 import org.spockframework.spring.SpringBean
50 import org.springframework.beans.factory.annotation.Autowired
51 import org.springframework.beans.factory.annotation.Value
52 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
53 import org.springframework.http.MediaType
54 import org.springframework.test.web.servlet.MockMvc
55 import spock.lang.Shared
56 import spock.lang.Specification
57
58 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNABLE_TO_READ_RESOURCE_DATA
59 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
60 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
61 import static org.springframework.http.HttpStatus.BAD_GATEWAY
62 import static org.springframework.http.HttpStatus.BAD_REQUEST
63 import static org.springframework.http.HttpStatus.CONFLICT
64 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
65 import static org.springframework.http.HttpStatus.NOT_FOUND
66 import static org.springframework.http.HttpStatus.PAYLOAD_TOO_LARGE
67 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
68 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
69
70 @WebMvcTest
71 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
72
73     @Autowired
74     MockMvc mvc
75
76     @SpringBean
77     NetworkCmProxyFacade mockNetworkCmProxyFacade = Mock()
78
79     @SpringBean
80     NetworkCmProxyInventoryFacadeImpl mockNetworkCmProxyInventoryFacade = Mock()
81
82     @SpringBean
83     InventoryPersistence mockInventoryPersistence = Mock()
84
85     @SpringBean
86     JsonObjectMapper stubbedJsonObjectMapper = Stub()
87
88     @SpringBean
89     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
90
91     @SpringBean
92     CmHandleStateMapper cmHandleStateMapper = Mappers.getMapper(CmHandleStateMapper)
93
94     @SpringBean
95     DataOperationRequestMapper dataOperationRequestMapper = Mappers.getMapper(DataOperationRequestMapper)
96
97     @SpringBean
98     DeprecationHelper stubbedDeprecationHelper = Stub()
99
100     @SpringBean
101     NcmpCachedResourceRequestHandler stubbedNcmpCachedResourceRequestHandler = Stub()
102
103     @SpringBean
104     NcmpPassthroughResourceRequestHandler StubbedNcmpPassthroughResourceRequestHandler = Stub()
105
106     @SpringBean
107     DataJobControllerForTest stubbedDataJobControllerForTest = Stub()
108
109     @SpringBean
110     RestOutputCmHandleMapper mockRestOutputCmHandleMapper = Mock()
111
112     @Value('${rest.api.ncmp-base-path}')
113     def basePathNcmp
114
115     @Value('${rest.api.ncmp-inventory-base-path}')
116     def basePathNcmpInventory
117
118     def dataNodeBaseEndpointNcmp
119     def dataNodeBaseEndpointNcmpInventory
120
121     @Shared
122     def sampleErrorMessage = 'some error message'
123     @Shared
124     def sampleErrorDetails = 'some error details'
125
126     def setup() {
127         dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
128         dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
129     }
130
131     def 'Get request with #scenario exception returns correct HTTP Status with #scenario exception'() {
132         when: 'an exception is thrown by the service'
133             setupTestException(exception, NCMP)
134             def response = performTestRequest(NCMP)
135         then: 'an HTTP response is returned with correct message and details'
136             assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
137         where:
138             scenario                | exception                                                                 || expectedErrorCode     | expectedErrorMessage        | expectedErrorDetails
139             'CPS'                   | new CpsException(sampleErrorMessage, sampleErrorDetails)                  || INTERNAL_SERVER_ERROR | sampleErrorMessage          | sampleErrorDetails
140             'NCMP-server'           | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails)           || INTERNAL_SERVER_ERROR | sampleErrorMessage          | null
141             'DMI Request'           | new DmiRequestException(sampleErrorMessage, sampleErrorDetails)           || BAD_REQUEST           | sampleErrorMessage          | null
142             'Invalid Operation'     | new InvalidOperationException('some reason')                              || BAD_REQUEST           | 'some reason'               | null
143             'Unsupported Operation' | new OperationNotSupportedException('not yet')                             || BAD_REQUEST           | 'not yet'                   | null
144             'DataNode Validation'   | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName')          || NOT_FOUND             | 'DataNode not found'        | null
145             'other'                 | new IllegalStateException(sampleErrorMessage)                             || INTERNAL_SERVER_ERROR | sampleErrorMessage          | null
146             'Data Node Not Found'   | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName')          || NOT_FOUND             | 'DataNode not found'        | 'DataNode not found'
147             'Existing entry'        | new AlreadyDefinedException('name',null)                                  || CONFLICT              | 'Already defined exception' | 'name already exists'
148             'Existing entries'      | AlreadyDefinedException.forDataNodes(['A', 'B'], 'myAnchorName')          || CONFLICT              | 'Already defined exception' | '2 data node(s) already exist'
149             'Operation too large'   | new PayloadTooLargeException(sampleErrorMessage)                          || PAYLOAD_TOO_LARGE     | sampleErrorMessage          | 'Check logs'
150             'Policy Executor'       | new PolicyExecutorException(sampleErrorMessage, sampleErrorDetails, null) || CONFLICT              | sampleErrorMessage          | sampleErrorDetails
151     }
152
153     def 'Post request with exception returns correct HTTP Status.'() {
154         given: 'the service throws data validation exception'
155             def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
156             setupTestException(exception, NCMPINVENTORY)
157         when: 'the HTTP request is made'
158             def response = performTestRequest(NCMPINVENTORY)
159         then: 'an HTTP response is returned with correct message and details'
160             assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
161     }
162
163     def 'Failing DMI Request - passthrough scenario'() {
164         given: 'failing DMI request'
165             setupTestException(new DmiClientRequestException(400, 'Error Message Details NCMP', 'Bad Request from DMI', UNABLE_TO_READ_RESOURCE_DATA), NCMP)
166         when: 'the DMI request is executed'
167             def response = performTestRequest(NCMP)
168         then: 'NCMP service responds with 502 Bad Gateway status'
169             response.status == BAD_GATEWAY.value()
170         and: 'the NCMP response also contains the original DMI response details'
171             response.contentAsString.contains('400')
172             response.contentAsString.contains('Bad Request from DMI')
173     }
174
175     def setupTestException(exception, apiType) {
176         if (NCMP == apiType) {
177             mockNetworkCmProxyInventoryFacade.getYangResourcesModuleReferences(*_) >> { throw exception }
178         }
179         mockNetworkCmProxyInventoryFacade.updateDmiRegistration(*_) >> { throw exception }
180     }
181
182     def performTestRequest(apiType) {
183         if (NCMP == apiType) {
184             return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
185         }
186         def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
187         return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
188     }
189
190     static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
191         assert response.status == expectedStatus.value()
192         def content = new JsonSlurper().parseText(response.contentAsString)
193         assert content['status'].toString().contains(expectedStatus.toString())
194         assert expectedErrorMessage == null || content['message'].toString().contains(expectedErrorMessage)
195         assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
196     }
197
198     enum ApiType { NCMP,  NCMPINVENTORY  }
199 }