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