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