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