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