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