2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 highstreet technologies GmbH
4 * Modifications Copyright (C) 2021-2024 Nordix Foundation
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.ncmp.rest.controller
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.impl.exception.DmiClientRequestException
30 import org.onap.cps.ncmp.api.impl.exception.DmiRequestException
31 import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException
32 import org.onap.cps.ncmp.api.inventory.NetworkCmProxyInventoryFacade
33 import org.onap.cps.ncmp.exceptions.PayloadTooLargeException
34 import org.onap.cps.ncmp.impl.data.NcmpCachedResourceRequestHandler
35 import org.onap.cps.ncmp.impl.data.NcmpPassthroughResourceRequestHandler
36 import org.onap.cps.ncmp.impl.data.NetworkCmProxyFacade
37 import org.onap.cps.ncmp.rest.util.CmHandleStateMapper
38 import org.onap.cps.ncmp.rest.util.DataOperationRequestMapper
39 import org.onap.cps.ncmp.rest.util.DeprecationHelper
40 import org.onap.cps.ncmp.rest.util.NcmpRestInputMapper
41 import org.onap.cps.spi.exceptions.AlreadyDefinedException
42 import org.onap.cps.spi.exceptions.CpsException
43 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
44 import org.onap.cps.spi.exceptions.DataValidationException
45 import org.onap.cps.utils.JsonObjectMapper
46 import org.spockframework.spring.SpringBean
47 import org.springframework.beans.factory.annotation.Autowired
48 import org.springframework.beans.factory.annotation.Value
49 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
50 import org.springframework.http.MediaType
51 import org.springframework.test.web.servlet.MockMvc
52 import spock.lang.Shared
53 import spock.lang.Specification
55 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNABLE_TO_READ_RESOURCE_DATA
56 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
57 import static org.onap.cps.ncmp.rest.controller.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
58 import static org.springframework.http.HttpStatus.BAD_GATEWAY
59 import static org.springframework.http.HttpStatus.BAD_REQUEST
60 import static org.springframework.http.HttpStatus.CONFLICT
61 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
62 import static org.springframework.http.HttpStatus.NOT_FOUND
63 import static org.springframework.http.HttpStatus.PAYLOAD_TOO_LARGE
64 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
65 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
68 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
74 NetworkCmProxyFacade mockNetworkCmProxyFacade = Mock()
77 NetworkCmProxyInventoryFacade mockNetworkCmProxyInventoryFacade = Mock()
80 JsonObjectMapper stubbedJsonObjectMapper = Stub()
83 NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
86 CmHandleStateMapper cmHandleStateMapper = Mappers.getMapper(CmHandleStateMapper)
89 DataOperationRequestMapper dataOperationRequestMapper = Mappers.getMapper(DataOperationRequestMapper)
92 DeprecationHelper stubbedDeprecationHelper = Stub()
95 NcmpCachedResourceRequestHandler stubbedNcmpCachedResourceRequestHandler = Stub()
98 NcmpPassthroughResourceRequestHandler StubbedNcmpPassthroughResourceRequestHandler = Stub()
100 @Value('${rest.api.ncmp-base-path}')
103 @Value('${rest.api.ncmp-inventory-base-path}')
104 def basePathNcmpInventory
106 def dataNodeBaseEndpointNcmp
107 def dataNodeBaseEndpointNcmpInventory
110 def sampleErrorMessage = 'some error message'
112 def sampleErrorDetails = 'some error details'
115 dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
116 dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
119 def 'Get request with #scenario exception returns correct HTTP Status with #scenario'() {
120 when: 'an exception is thrown by the service'
121 setupTestException(exception, NCMP)
122 def response = performTestRequest(NCMP)
123 then: 'an HTTP response is returned with correct message and details'
124 assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
126 scenario | exception || expectedErrorCode | expectedErrorMessage | expectedErrorDetails
127 'CPS' | new CpsException(sampleErrorMessage, sampleErrorDetails) || INTERNAL_SERVER_ERROR | sampleErrorMessage | sampleErrorDetails
128 'NCMP-server' | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails) || INTERNAL_SERVER_ERROR | sampleErrorMessage | null
129 'DMI Request' | new DmiRequestException(sampleErrorMessage, sampleErrorDetails) || BAD_REQUEST | sampleErrorMessage | null
130 'Invalid Operation' | new InvalidOperationException('some reason') || BAD_REQUEST | 'some reason' | null
131 'Unsupported Operation' | new OperationNotSupportedException('not yet') || BAD_REQUEST | 'not yet' | null
132 'DataNode Validation' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || NOT_FOUND | 'DataNode not found' | null
133 'other' | new IllegalStateException(sampleErrorMessage) || INTERNAL_SERVER_ERROR | sampleErrorMessage | null
134 'Data Node Not Found' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || NOT_FOUND | 'DataNode not found' | 'DataNode not found'
135 'Existing entry' | new AlreadyDefinedException('name',null) || CONFLICT | 'Already defined exception' | 'name already exists'
136 'Existing entries' | AlreadyDefinedException.forDataNodes(['A', 'B'], 'myAnchorName') || CONFLICT | 'Already defined exception' | '2 data node(s) already exist'
137 'Operation too large' | new PayloadTooLargeException(sampleErrorMessage) || PAYLOAD_TOO_LARGE | sampleErrorMessage | 'Check logs'
140 def 'Post request with exception returns correct HTTP Status.'() {
141 given: 'the service throws data validation exception'
142 def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
143 setupTestException(exception, NCMPINVENTORY)
144 when: 'the HTTP request is made'
145 def response = performTestRequest(NCMPINVENTORY)
146 then: 'an HTTP response is returned with correct message and details'
147 assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
150 def 'Failing DMI Request - passthrough scenario'() {
151 given: 'failing DMI request'
152 setupTestException(new DmiClientRequestException(400, 'Error Message Details NCMP', 'Bad Request from DMI', UNABLE_TO_READ_RESOURCE_DATA), NCMP)
153 when: 'the DMI request is executed'
154 def response = performTestRequest(NCMP)
155 then: 'NCMP service responds with 502 Bad Gateway status'
156 response.status == BAD_GATEWAY.value()
157 and: 'the NCMP response also contains the original DMI response details'
158 response.contentAsString.contains('400')
159 response.contentAsString.contains('Bad Request from DMI')
162 def setupTestException(exception, apiType) {
163 if (NCMP == apiType) {
164 mockNetworkCmProxyInventoryFacade.getYangResourcesModuleReferences(*_) >> { throw exception }
166 mockNetworkCmProxyInventoryFacade.updateDmiRegistrationAndSyncModule(*_) >> { throw exception }
169 def performTestRequest(apiType) {
170 if (NCMP == apiType) {
171 return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
173 def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
174 return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
177 static void assertTestResponse(response, expectedStatus, expectedErrorMessage, expectedErrorDetails) {
178 assert response.status == expectedStatus.value()
179 def content = new JsonSlurper().parseText(response.contentAsString)
180 assert content['status'].toString().contains(expectedStatus.toString())
181 assert expectedErrorMessage == null || content['message'].toString().contains(expectedErrorMessage)
182 assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
185 enum ApiType { NCMP, NCMPINVENTORY }