1258e6e1c418c78fb5e2d88f416c6526f70d00fb
[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-2022 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.mapper.RestOutputCmHandleStateMapper
33 import org.onap.cps.spi.exceptions.CpsException
34 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
35 import org.onap.cps.spi.exceptions.DataValidationException
36 import org.onap.cps.utils.JsonObjectMapper
37 import org.spockframework.spring.SpringBean
38 import org.springframework.beans.factory.annotation.Autowired
39 import org.springframework.beans.factory.annotation.Value
40 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
41 import org.springframework.http.HttpStatus
42 import org.springframework.http.MediaType
43 import org.springframework.test.web.servlet.MockMvc
44 import spock.lang.Shared
45 import spock.lang.Specification
46
47 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
48 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
49 import static org.springframework.http.HttpStatus.BAD_REQUEST
50 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
51 import static org.springframework.http.HttpStatus.NOT_FOUND
52 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
53 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
54
55 @WebMvcTest
56 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
57
58     @Autowired
59     MockMvc mvc
60
61     @SpringBean
62     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
63
64     @SpringBean
65     JsonObjectMapper jsonObjectMapper = Stub()
66
67     @SpringBean
68     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
69
70     @SpringBean
71     RestOutputCmHandleStateMapper restOutputCmHandleStateMapper = Mappers.getMapper(RestOutputCmHandleStateMapper)
72
73     @Value('${rest.api.ncmp-base-path}')
74     def basePathNcmp
75
76     @Value('${rest.api.ncmp-inventory-base-path}')
77     def basePathNcmpInventory
78
79     def dataNodeBaseEndpointNcmp
80     def dataNodeBaseEndpointNcmpInventory
81
82     @Shared
83     def sampleErrorMessage = 'some error message'
84     @Shared
85     def sampleErrorDetails = 'some error details'
86
87     def setup() {
88         dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
89         dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
90     }
91
92     def 'Get request with generic #scenario exception returns correct HTTP Status with #scenario'() {
93         when: 'an exception is thrown by the service'
94             setupTestException(exception, NCMP)
95             def response = performTestRequest(NCMP)
96         then: 'an HTTP response is returned with correct message and details'
97             assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
98         where:
99             scenario              | exception                                                        || expectedErrorDetails | expectedErrorMessage | expectedErrorCode
100             'CPS'                 | new CpsException(sampleErrorMessage, sampleErrorDetails)         || sampleErrorDetails   | sampleErrorMessage   | INTERNAL_SERVER_ERROR
101             'NCMP-server'         | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
102             'NCMP-client'         | new DmiRequestException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | BAD_REQUEST
103             'DataNode Validation' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || null                 | 'DataNode not found' | NOT_FOUND
104             'other'               | new IllegalStateException(sampleErrorMessage)                    || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
105             'Data Node Not Found' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || 'DataNode not found' | 'DataNode not found' | NOT_FOUND
106     }
107
108     def 'Post request with exception returns correct HTTP Status.'() {
109         given: 'the service throws data validation exception'
110             def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
111             setupTestException(exception, NCMPINVENTORY)
112         when: 'the HTTP request is made'
113             def response = performTestRequest(NCMPINVENTORY)
114         then: 'an HTTP response is returned with correct message and details'
115             assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
116     }
117
118     def 'Failing DMI Request - passthrough scenario'() {
119         given: 'failing DMI request'
120             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(*_) >> { throw new HttpClientRequestException('Error Message Details NCMP', 'Bad Request from DMI', 400) }
121         when: 'the DMI request is executed'
122             def response = mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running?resourceIdentifier=stores:bookstore/categories=100"))
123                 .andReturn().response
124         then: 'NCMP service responds with 502 Bad Gateway status'
125             response.status == HttpStatus.BAD_GATEWAY.value()
126         and: 'the NCMP response also contains the original DMI response details'
127             response.contentAsString.contains('400')
128             response.contentAsString.contains('Bad Request from DMI')
129     }
130
131     def setupTestException(exception, apiType) {
132         if (NCMP == apiType) {
133             mockNetworkCmProxyDataService.getYangResourcesModuleReferences(*_) >> { throw exception }
134         }
135         mockNetworkCmProxyDataService.updateDmiRegistrationAndSyncModule(*_) >> { throw exception }
136     }
137
138     def performTestRequest(apiType) {
139         if (NCMP == apiType) {
140             return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
141         }
142         def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
143         return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
144     }
145
146     static void assertTestResponse(response, expectedStatus , expectedErrorMessage , expectedErrorDetails) {
147         assert response.status == expectedStatus.value()
148         def content = new JsonSlurper().parseText(response.contentAsString)
149         assert content['status'].toString().contains(expectedStatus.toString())
150         assert content['message'].toString().contains(expectedErrorMessage)
151         assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
152     }
153
154     enum ApiType {
155         NCMP,
156         NCMPINVENTORY;
157     }
158 }